Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UpdateExistingPivot for multiple ids

In order to update single record in pivot table I use updateExistingPivot method. However it takes $id as the first argument. For example:

$step->contacts()->updateExistingPivot($id, [
    'completed' => true,
    'run_at' => \Carbon\Carbon::now()->toDateTimeString()
]);

But how can I update multiple existing rows in pivot table at once?

like image 579
Victor Avatar asked Apr 18 '16 12:04

Victor


1 Answers

There's an allRelatedIds() method in the BelongsToMany relation that you can access, which will return a Collection of the related model's ids that appear in the pivot table against the initial model.

Then a foreach will do the job:

$ids = $step->contacts()->allRelatedIds();

foreach ($ids as $id){
    $step->contacts()->updateExistingPivot($id, ['completed' => true]);
}
like image 72
jwj Avatar answered Nov 10 '22 00:11

jwj