Home > Back-end >  The equivalent of `syncWithPivotValues` for `attach` method in Laravel 9
The equivalent of `syncWithPivotValues` for `attach` method in Laravel 9

Time:06-16

In Laravel 9, there's syncWithPivotValues, which can sync several records with passed pivot values. Is there such thing for attach method? Basically I want to perform attach to several records with the same pivot values, such as:

// attach `role` 1, 2, 3 to `$user`; with `active` attribute set to `true`
$user->roles()->attach([1, 2, 3], ['active' => true]);

CodePudding user response:

You can do something like this:

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

Resource: https://laravel.com/docs/9.x/eloquent-relationships#updating-many-to-many-relationships

If you don't want to repeat ['active' => true] all the time, you can use array_fill_keys like this: array_fill_keys([1, 2, 3], ['active' => true]) so your code will look like:

$user->roles()->attach(array_fill_keys([1, 2, 3], ['active' => true]));

Resource: https://www.php.net/manual/en/function.array-fill-keys.php

  • Related