phplaravelloopseloquentlaravel-5.4

Laravel : Many to many insertion


I have two models, User and Team The relationship between them is 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 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 first member_id. I want it to create one record per member from the members_id array. How am i gonna do that ?


Solution

  • You should pass an array of user IDs to the attach() method.

    For convenience, attach and detach also accept arrays of IDs as input

    Change your code to:

    $team = \App\Team::findOrFail($request->team_id);
    $team->teamMembers()->attach($request->members_id);