In Laravel, is there a way to syncWithoutDetaching and also update pivot values?

681 Views Asked by At

According to the API documentation:

syncWithPivotValues: sync the intermediate tables with a list of IDs or collection of models with the given pivot values.

syncWithouDetaching: sync the intermediate tables with a list of IDs without detaching.

How can I sync the intermediate tables with a list of IDs without detaching with the given pivot values?

Example:

The following operation will adds roles with IDs 1, 2, and 3 to the user and sets the active pivot attribute to true for these roles.

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

The above will also sync the $user and their roles but it adds these roles without detaching any existing roles.

$user->roles()->syncWithoutDetaching([1, 2, 3]);

What I want to do:

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

Basically I'm looking for a way to add these roles to the $user without detaching any existing roles, but also set the active pivot attribute to true for these newly added roles.

1

There are 1 best solutions below

1
Salman Hider On

I use syncWithoutDetaching like this:

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