roles
roles copied to clipboard
Sync Roles
I was curious as to why there is no Sync feature for Roles?
Something along the lines of this? Are there any known issues with syncing roles?
public function syncRoles(array $role)
{
$this->roles = null;
return $this->roles()->sync($role);
}
i try this function as you declared it and it gives error on updating user and did not select any roles so i change the your declaration to be
public function syncRoles($roles = array())
{
$this->roles = null;
return empty($roles) ? $this->detachAllRoles() : $this->roles()->sync($roles);
}
this works for me without any errors :+1:
Awesome thanks!
Just checked your code, it works great, but you lose the sync attributes if array is empty, since it will detach and not sync.
$user = User::find($request->get('user_id'));
$roles = $request->get('roles');
$sync = $user->syncRoles($roles);
foreach ($sync['attached'] as $role_id) {
//log changes?
}
foreach ($sync['detached'] as $role_id) {
//log changes?
}
when using your version of the function you probably would get error as i got because the syncRoles function expects its parameter ($roles) to be an array but when you deselect all roles the $request->get('roles'); will return null so error will appear and to avoid this error you could use my version of the syncRoles function or you should change the type of the parameter when passing it to the function like this
$user->syncRoles((array) $request->get('roles'));
thanks
You're right about that!
Thanks, I need to do something like this for both roles and permissions.
https://github.com/mackhankins/roles and https://github.com/sw-double/roles both have that feature now.