Video Course

Laravel Eloquent Relationships: Lesson 7 of 7

Sync

It can be tedious to check if many-to-many relationships exist before adding or removing them. The sync method provides a convenient way to only let the given ids be left. Anything not in the given ids will be removed.

// attach roles 1, 2, 3
$users->roles()->attach([1, 2, 3]);

// sync roles 1, 5, 7
$user->roles()->sync([1, 5, 7]);

// the resulting roles are 1, 5, 7
// 2, 3 were removed automatically
// 5, 7 were added automatically

Chris Sevilleja

157 posts

Co-founder of Scotch.io. Slapping the keyboard until something good happens.