Laravel, sync() - how to sync an array and also pass additional pivot fields?
In order to sync
multiple models along with custom pivot data, you need this:
$user->roles()->sync([
1 => ['expires' => true],
2 => ['expires' => false],
...
]);
Ie.
sync([
related_id => ['pivot_field' => value],
...
]);
edit
Answering the comment:
$speakers = (array) Input::get('speakers'); // related ids
$pivotData = array_fill(0, count($speakers), ['is_speaker' => true]);
$syncData = array_combine($speakers, $pivotData);
$user->roles()->sync($syncData);
This works for me
foreach ($photos_array as $photo) {
//collect all inserted record IDs
$photo_id_array[$photo->id] = ['type' => 'Offence'];
}
//Insert into offence_photo table
$offence->photos()->sync($photo_id_array, false);//dont delete old entries = false
There is now a ->syncWithPivotValues($ids, $pivotValues)
method available if you want to set the same pivot value for all synced items.
Example from the doc:
$user->roles()->syncWithPivotValues([1, 2, 3], ['active' => true]);