Laravel Eloquent – Attach vs Sync

Qual é a diferença entre attach () e sync () no Eloquent ORM?


  • Insert related models when working with many-to-many relations
  • No array parameter is expected


$user = User::find(1);



Similar to the attach() method. sync() also use to attach related models. However main difference is:

  • Sync method accepts an array of IDs to place on the pivot table
  • Secondly, most important, The sync method will delete the models from table if model does not exist in array and insert new items to the pivot table.



id  user_id role_id
1    2       1
2    2       5
3    2       2
$user->roles()->sync(array(1, 2, 3));

The above operation will delete:

id  user_id role_id
2    2       5

And insert role_id 3 to the table.

user_role table

id  user_id role_id
1    2       1
3    2       2
4    2       3

To make it even simpler:

The attach function only add records to the Pivot table.

The sync function replaces the current records with the new records. This is very useful for updating a model.


Assuming you have a created Post that has many Tags attached on it where the Tags ID’s are [1,2,3].

And the user has the ability to update the Post and its Tags.

The user will send you the new Tags ID’s [3,4,5].

If you use the sync function, the new Tags of the Post will be [3,4,5] only.

But if you use the attach function, the new Tags of the Post will be [1,2,3,4,5].

Resultado de imagem para laravel

Renato Lucena

Developer PHP, Laravel. Goiania-GO

Você pode gostar...