I have this schema for the M-M table in laravel 9
Schema::create('role_user', function(Blueprint $table)) {
$table->bigInteger('role_id')->unsigned();
$table->foreign('role_id')->references('id')->on('roles');
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->bigInteger('business_unit_id')->unsigned();
$table->primary(['role_id', 'user_id', 'business_unit_id']);
}
The idea is that for each business unit the user has a different role.
I tried to save the data using:
$user->roles()->syncWithoutDetaching([$role->id => ['business_unit_id' => $businessUnitId]]);
is not working properly…
How can I sync all the data based on the current ‘business_unit_id’ without touching the other entries (with other business_unit_id) ?
>Solution :
To sync all the data based on the current ‘business_unit_id’ without touching the other entries (with other business_unit_id), you can use the wherePivot method in Laravel. Here’s an example:
$user->roles()->wherePivot('business_unit_id', $businessUnitId)->sync([$role->id]);
This will synchronize the pivot table for the given user and role, but only for the specified business_unit_id. The wherePivot method filters the pivot table records by the specified condition before performing the sync operation.
Note that the sync method replaces all existing entries in the pivot table for the given user and role, so you may want to use syncWithoutDetaching if you want to add the new record without deleting the existing ones.