mardi 31 mai 2016

Model pivot not attaching properly after detaching all

I have a custom developed user/roles functionality with a roles table and a user_roles intermediate table. The user_roles table also has some additional data.

Lets suppose a user currently has 1 role assigned to him, and i have to assign 2 more roles to this user. Mostly i just detach all pivot enteries for the user, and then add all 3 roles again. This simplifies things and i dont have to check the json data for duplicate enteries. Something like this.

$user->roles()->detach();

This works fine and all the user pivot entries are removed. But when i attach all 3 roles again to the user, only the new ones are added. This is really weird and have been trying to debug it for a few hours now.

I loop through all 3 roles and i made sure that the loop is actually receiving this data properly.

$apps = json_encode(array('app1','app2'));
$user->roles()->attach($roleId, ['apps' => $apps]);

I remember that i faced a very similar issue earlier on another project as well, but dont remember the solution. Any help would be appriciated.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire