Difference between attach() and sync() in Laravel

attach() inserts related models when working with many-to-many relations and no array parameter is expected.

example:

$user = User::find(1);

$user->roles()->attach(1);

sync()

It is similar to the attach() method and it also use to attach related models. sync() method accepts an array of IDs to place on the pivot table.If the models doesnot exist in array the sync method will delete models from table and insert new items to the pivot table.

example:

user_role

id  user_id role_id

1    2   1

2    2   5

3    2   2

$user->roles()->sync(array(1, 2, 3));

This will delete :

id  user_id role_id

2    2   5

and insert role_id 3

user_role table

id  user_id role_id

1    2   1

3    2   2

4    2   3