0

I'm wondering if there is a difference between the two following Eloquent instructions that update the data on the role_user pivot table of a many-to-many relationship between User and Role models.

// Attach the specified roles to the user
$user–>roles()–>attach([1, 2, 3]);

// Sync the specified roles without detaching the one previously assigned to the user
$user–>roles()–>syncWithoutDetaching([1, 2, 3]);

I think they do the same thing, am I correct?

Davide Casiraghi
  • 15,591
  • 9
  • 34
  • 56
  • have you ran this to see? – lagbox Jan 27 '21 at 12:37
  • I did now in Tinkerwell. I got the same result. What changes is the return value. From attach() is always null in any case. From syncWithoutDetaching() I get an array as return value. With the ids of the field attached, detached and updated. I guess that detached will always be empty in this case. [ "attached" => [], "detached" => [], "updated" => [], ] – Davide Casiraghi Jan 27 '21 at 12:47
  • did you make sure that this pivot table already has records matching `1, 2, 3` before running `syncWithoutDetaching` then see what the table looks like? did you then after that run `attach` and look at the pivot table? as that would answer this for you – lagbox Jan 27 '21 at 12:48
  • I'm not getting why somebody voted down. To me seems an interesting question moved by curiosity to understand beyond the contents of the documentation. – Davide Casiraghi Jan 27 '21 at 12:48
  • Yes, I checked the pivot table after running both.. – Davide Casiraghi Jan 27 '21 at 12:50
  • what happened after you ran `attach`? – lagbox Jan 27 '21 at 12:51
  • It added the 3 values to the pivot table. I can confirm that even when attach() add new values it returns null. – Davide Casiraghi Jan 27 '21 at 12:51
  • the return value doesn't matter ... what happens in the database is what matters ... so is there a difference in what happened in the database with those 2 different methods? – lagbox Jan 27 '21 at 12:52
  • Same result it the database, when not present they both add 3 rows to the role_user table with the corresponding keys. And they didn't remove or update anything when they are already present. – Davide Casiraghi Jan 27 '21 at 12:53
  • 1
    same result ... did `syncWithoutDetaching` add new records or not? did `attach` add new records or not? run `syncWithoutDetaching` 5 times, are there 5 times as many new records? run `attach` 5 times, are there 5 times more records? – lagbox Jan 27 '21 at 12:54

1 Answers1

1

"attach" method inserts the array argument without syncing or removing existing data while "syncWithoutDetaching" method updates the existing value comparing with array argument and also does not remove rest of the existing values.

  • sync vs syncWithoutDetaching, explained [1](https://stackoverflow.com/questions/23968415/laravel-eloquent-attach-vs-sync) [2](https://www.amitmerchant.com/attach-detach-sync-laravel/) – tinystone Jul 18 '23 at 06:59