When updating a model and I sync a relationship, if I don't pass in all the ids that already exist, will that relationship be removed?
Asked
Active
Viewed 9,416 times
2 Answers
24
You decide: sync
has 2nd parameter that defaults to true
and is responsible for detaching:
$model->relationship()->sync([1,2,3]);
$model->relationship()->sync([4,5,6]); // attached [4,5,6], detached [1,2,3]
$model->relationship()->getRelatedIds(); // [4,5,6]
// but:
$model->relationship()->sync([4,5,6], false); // attached [4,5,6], detached []
$model->relationship()->getRelatedIds(); // [1,2,3,4,5,6]

Jarek Tkaczyk
- 78,987
- 25
- 159
- 157
-
1But if I remove all the Tags, `sync()` does not do anything at all. How can you make it work in this case? For example, if previously you have `[1,2,3]` inside the relational table and want to make a `sync([])` because you have removed all the tags from the Select2. How do you delete all the tags then? – Pathros Feb 25 '16 at 22:43
0
The answer is Yes it does. I could not find any documentation that in fact stated that.
lets say you have 2 tables: "authors" and "books", with a pivot table "book_authors".
when creating a new author:
$author_id =2;
$author->books()->sync(array(1,4,5,15));
Now you have a 4 entries in that pivot table "book_authors":
author_id book_id
2 1
2 4
2 5
2 15
Now update:
$author_id =2;
$author->books()->sync(array(1,15));
now "book_authors" is:
author_id book_id
2 1
2 15

Jason Spick
- 6,028
- 13
- 40
- 59
-
1I can confirm. `sync()` method is supposed to remove relations that don't exist anymore and keep relations that are still relevant. – Andreyco Jun 13 '14 at 16:11
-
But if I remove all the Tags, sync() does not do anything at all. How can you make it work in this case? For example, if previously you have [1,4,5,15] inside the relational table and want to make a sync([]) because you have removed all the tags from the Select2. How do you delete all the tags then? – Pathros Feb 25 '16 at 22:44
-
You can use relation to delete it like. `$author->books->delete();` – Lizesh Shakya Sep 01 '20 at 04:48