Bryan Miller
Bryan Miller

Reputation: 3323

Pivot table with identical IDs but different intermediate table values

The Laravel docs say this:

You may also pass additional intermediate table values with the IDs: $user->roles()->sync([1 => ['notes' => true], 2, 3]);

I am wondering if it is possible to do something like this:

$user->roles()->sync([1 => ['notes' => true], 1 => ['notes' => false]]);

I am doing the above currently in a slightly different way, and Laravel appears to be simply overwriting the 1st entry in the pivot table with the 2nd entry, so the pivot table looks like this:

user    role  notes
1       1     false

Is there a way to use sync() so that it will save both values in the pivot table, so it would look like this?

user    role  notes
1       1     true
1       1     false

If sync() cannot do this for me, is there a different way of creating the desired result?

Upvotes: 0

Views: 62

Answers (1)

Bryan Miller
Bryan Miller

Reputation: 3323

You can use attach() instead like this:

$user->roles()->attach(1, ['notes' => true]);
$user->roles()->attach(1, ['notes' => false]);

and if you want to erase previous values, you can use sync() with an empty array before doing the above like this:

$user->roles()->sync([]);
$user->roles()->attach(1, ['notes' => true]);
$user->roles()->attach(1, ['notes' => false]);

and then the result you will have will be the desired result in the DB:

user    role  notes
1       1     true
1       1     false

Upvotes: 0

Related Questions