A three way pivot is hell.
In this situation try to introduce another model to get back to classic two sided relationship. Here try to add a model representig the couple User/Project, which has a classic hasMany relationship with Role.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hey guys,
Im wondering how i can get my sync working with when using a three way pivot table.
What i have tried so far is:
public function projects()
{
return $this->belongsToMany('App\Project', 'project_user', 'user_id', 'project_id')->withPivot('role_id');
}
Use the sync method:
$user->projects()->sync($projects, array('role_id' => $roles));
But this is not updating my role_id field inside the pivot table.
I have no idea what i do wrong here and hope someone can explain to me how to get this working.
@kazehaya You're doing it wrong ;)
$user->projects()->sync([
1 => ['role_id' => $roles],
4 => ['role_id' => $roles],
9 => ['role_id' => $roles],
]);
This is how sync works when you want to update existing rows (as well as insert new ones). 1, 4 and 9 are projects ids, so just build an array that looks like this.
For triple pivot you can use this https://github.com/jarektkaczyk/Eloquent-triple-pivot/ , however mind that it is not complete and I'm not working on it anymore.
Please or to participate in this conversation.