'Laravel Eloquent - Attach vs. SyncWithoutDetaching
What is the difference between syncWithoutDetaching and attach in Laravel?
Solution 1:[1]
Let's assume that you have auto-increment primary key id in your pivot table, you will notice:
attach()will add the new records to the pivot table, and pre-existed relations will get fresh ids.sync()will remove all existed relations and set only provided in current request, with fresh ids too.syncWithoutDetaching()will remove all existed relations except provided in current process, then the pre-existed rows won't get new ids.
Solution 2:[2]
Two things:
attach()will always add a new record to the pivot table, whereassyncWithoutDetaching()will only add a new record if one does not exist.
Let's say you have orders and items.
$order->items()->attach(1);
$order->items()->attach(1);
// $order->items()->count() === 2
$order2->items()->syncWithoutDetaching(1);
$order2->items()->syncWithoutDetaching(1);
// $order2->items()->count() === 1
attach()returnsnull, whereassyncWithoutDetaching()returns an array showing what was attached/detached/updated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | patricus |
