Laravel : Many to many insertion

35,878

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);
Share:
35,878

Related videos on Youtube

Gammer
Author by

Gammer

Just another day, Trying to learn. That's it.

Updated on January 12, 2020

Comments

  • Gammer
    Gammer over 4 years

    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 ?

  • Gammer
    Gammer about 7 years
    Perfect, i just forgot to pass the array. Thanks dude
  • Evis
    Evis almost 7 years
    @Alexey, there is the syncoption too, you could update the answer to have it fullfilled, just a suggestion. Cheers!