0

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]);

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply, but my point is that I don't want to write the 'active' => true 3 times. Is that possible?
@rifqyabdl I updated my answer so it is shorter now. Unfortunately you can't do that what you want, but you can use some trickery to achieve the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.