I have two models: Userand the Team
relationship between them ManyToMany:
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 command. Therefore, the name of the pivot table team_user.
Now the data that I want to insert into the pivot table is as follows:
array:4 [▼
"_token" => "mlwoAgCQYals1N1s2lNa4U5OTgtMNHh9LUhNGrWh"
"team_id" => "1"
"members_id" => array:3 [▼
0 => "2"
1 => "3"
2 => "4"
]
"status" => "1"
]
What I do 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 he only inserts one record, I mean the team_idfirst member_id. I want him to create one record for each member from the array members_id. How do i do this?
source
share