Official Laravel documentation has this on sync()
function:
$user->roles()->sync( array( 1, 2, 3 ) );
You may also associate other pivot table values with the given IDs:
$user->roles()->sync( array( 1 => array( 'expires' => true ) ) );
In the latter example only a single pivot row is being added. What I don't understand is how can I associate other pivot table records if there are more than one rows to be synced?
Thanks in advance.
01 Use Of Sync In LaravelThe sync() method accepts an array as an argument. As the name suggests, this method synchronizes the database entries that means whatever you pass in this method, those records will be kept into the database and the rest will be removed from the intermediate(pivot) table.
So in simple words we can say: sync() is similar to the attach() method and it also use to attach related models. sync() method accepts an array of IDs to place on the pivot table. If the models does not exist in array the sync method will delete models from table and insert new items to the pivot table.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With