9

I have Googled my fingers sore, and I can't see anyone discussing this, but I have a suspicion that Laravels syncWithoutDetaching() method doesn't take any parameters for extra data like save(), sync() and attach() does?

Does anybody know this? In the API documentation the method has the following parameters:

array syncWithoutDetaching(Collection|Model|array $ids)

I have trouble adding existing data to a relationship between a Guest and an Event. I need to add status for the guests and what event they are attending, maybe attending or declined.

rebellion
  • 6,628
  • 11
  • 48
  • 79

2 Answers2

9

sync() and syncWithoutDetaching() both don't have a parameter for additional values, you have to pass the additional values as an array with the ids.


According to the docs:

You may also pass additional intermediate table values with the IDs:

$user->roles()->sync([
    1 => ['expires' => true],
    2,
    3
]);


If you look here you can see that syncWithoutDetaching() just calls sync() but passes false as the second argument.

In your case it would be something like this:

$event->guests()->syncWithoutDetaching([
    1 => ['attending' => true],
    2 => ['attending' => false]
])
Travis Britz
  • 5,094
  • 2
  • 20
  • 35
Remul
  • 7,874
  • 1
  • 13
  • 30
3

I think @remul answer is the best, but it requires additions for people like me who get to this page.

syncWithoutDetaching() - is just an abbreviation for sync() - here. This corresponds to sync($data, false)

The documentation talks about another great method:

If you would like to insert the same intermediate table values with each of the synced model IDs, you may use the syncWithPivotValues method

But the documentation does not say that the method accepts the third argument, which just corresponds to the logic of syncWithoutDetaching().

Look here. If you pass false, the IDs not passed will not be detaching.

I think this is what the question was about.