Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel, sync() - how to sync an array and also pass additional pivot fields?

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.

like image 918
Томица Кораћ Avatar asked Dec 01 '14 14:12

Томица Кораћ


People also ask

How do I sync a pivot table in Laravel?

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.

What is sync function in Laravel?

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.


3 Answers

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);
like image 55
Jarek Tkaczyk Avatar answered Oct 16 '22 13:10

Jarek Tkaczyk


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
like image 56
stackflow Avatar answered Oct 16 '22 13:10

stackflow


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]);
like image 14
Robin Avatar answered Oct 16 '22 12:10

Robin