Laravel : Many to many insertion
35,878
You should pass an array of user IDs to the attach()
method.
For convenience,
attach
anddetach
also accept arrays of IDs as input
Change your code to:
$team = \App\Team::findOrFail($request->team_id);
$team->teamMembers()->attach($request->members_id);
Related videos on Youtube
Comments
-
Gammer over 4 years
I have two models,
User
andTeam
The relationship between them isManyToMany
:In
User
:public function teamMembers(){ return $this->belongsToMany('App\Team')->withPivot('id');; }
And in
Team
:public function teamMembers(){ return $this->belongsToMany('App\User')->withPivot('id');; }
Now i want to add users to a specific team. So the pivot table name is
team_user
.Now the data i want to insert to pivot table is :
array:4 [▼ "_token" => "mlwoAgCQYals1N1s2lNa4U5OTgtMNHh9LUhNGrWh" "team_id" => "1" "members_id" => array:3 [▼ 0 => "2" 1 => "3" 2 => "4" ] "status" => "1" ]
What i am doing in my controller :
$team_id = $request->get("team_id"); $team = \App\Team::findOrFail($team_id); foreach ($request->get('members_id') as $key => $value) { $team->teamMembers()->attach($team); $team->save(); }
But it only inserts one record, I mean the
team_id
and the firstmember_id
. I want it to create one record per member from themembers_id
array. How am i gonna do that ? -
Gammer about 7 yearsPerfect, i just forgot to pass the array. Thanks dude
-
Evis almost 7 years@Alexey, there is the
sync
option too, you could update the answer to have it fullfilled, just a suggestion. Cheers!