LoveCoding
LoveCoding

Reputation: 1211

Laravel Many to Many Sync with additional column

Laravel version 7.0

I have Team model and User model, team_has_users table.

team_has_users table has team_id, user_id, role columns.

One user can belong to one team with different roles.

For instance, one user can belong to one team as a client and as an employee.

in Team model, I set a relation like this.

public function users(){
   return $this->belongsToMany(User::class, 'team_has_user', 'team_id', 'user_id')
       ->withPivot('role');
}

When I attach users to the team, it worked well like this.

    $item->users()->attach($request->clients, ['role'=>'client']);
    $item->users()->attach($request->employees, ['role'=>'employee']);

But, when I was going to sync them, I couldn't do.

I tried to search and found a similar one syncwithoutDetaching but it seems not to fit for my case. team_has_users table can be like this.

team_id    user_id    role
1           1         client
1           1         employee
1           2         client
1           1         other
...

Can anyone help me?

Thank you!

Upvotes: 6

Views: 3823

Answers (1)

Dilip Hirapara
Dilip Hirapara

Reputation: 15296

While attach you can pass an additional array as you have passed.

$item->users()->attach($request->clients, ['role'=>'client']);
$item->users()->attach($request->employees, ['role'=>'employee']);

But In the sync you have to pass pivot value inside the array, I have mention example below.

$item->roles()->sync([1 => ['role' => 'client'], 2 => ['role' => 'employee']);

Check documentation sync part,

Upvotes: 6

Related Questions