I’m only starting with laravel and was wondering if anyone could help, I’ve created a friend_id and user_id from the database and have made a form in the view that adds the user_id to the friend_id (not sure what the terminology is for anything yet XD) everything working fine but each time I press the add friend button the friend user duplicates, so my question is how do I add a user without the user duplicating data?
FriendsController
public function store(Request $request)
{
//check I have a post with a friend id
$validator = Validator::make($request->all(), [
'friend_id' => 'required'
]);
if ($validator->fails()) {
return redirect('/posts')
->withErrors($validator)
->withInput();
}
//get the current user
$user = Auth::user();
//attach friend to current user
$data = [
'friend_id' => $request->input('friend_id'),
'user_id' => $user->id,
];
$friend = $user->friends()->where('friend_id', $request->input('friend_id'))->get();
$friend = $user->friends()->create($data);
//redirect back to XXX
return redirect('/posts');
}
<div class="row justify-content-md-center">
<div class="col-3 mt-3">
@foreach ($friends as $friend)
<form method="post" action="/friends">
@csrf
<div class="text-center border p-2">
{{ $friend->id }}
{{ $friend->name }}
<div class="row justify-content-center">
<button type="submit" name="friend_id" value="{{$friend->id}}" class="btn btn-primary">Add Friend</button>
</div>
</div>
</form>
@endforeach
</div>
</div>
This is what my boss suggested and it works to only add one friend id in the database at all
//check I have a post with a friend id
$validator = Validator::make($request->all(), [
'friend_id' => 'required'
]);
if ($validator->fails()) {
return redirect('/posts')
->withErrors($validator)
->withInput();
}
//get the current user
$user = Auth::user();
//attach friend to current user
$data = [
'friend_id' => $request->input('friend_id'),
'user_id' => $user->id,
];
$friend = $user->friends()->where('friend_id', $request->input('friend_id'))->get();
if(!$friend)
{
$friend = $user->friends()->create($data);
}
Advertisement
Answer
you can do this easily with a firstOrCreate :
public function store(Request $request)
{
$request->validate([
'friend_id' => 'required'
]);
auth()->user()->friends()->firstOrCreate([
'friend_id' => $request->friend_id
]);
}
But the logic is quite a bit wrong,
as I guess, your friends() relation on the User Model refer to a pivot table between 2 users (sort of)
You should just do this :
Pivot table :
id | user_id | friend_id
User Model :
public function friends(){
return $this->belongsToMany(User::class, 'friends', 'user_id', 'friend_id');
}
then in your controller :
auth()->user()->friends()->syncWithoutDetaching([$request->friend_id]);