attach() will always add a new record to the pivot table, whereas syncWithoutDetaching() will only add a new record if one does not exist.
$order->items()->attach(1);
$order->items()->attach(1);
// $order->items()->count() === 2
$order2->items()->syncWithoutDetaching(1);
$order2->items()->syncWithoutDetaching(1);
// $order2->items()->count() === 1
sync(Array, false) is the same as syncWithoutDetaching():
public function syncWithoutDetaching($ids)
{
return $this->sync($ids, false);
}
In short, by default sync() detaches.
Leave a Reply