roles icon indicating copy to clipboard operation
roles copied to clipboard

Sync Roles

Open amberlampsio opened this issue 9 years ago • 7 comments

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);
 }

amberlampsio avatar Nov 04 '15 18:11 amberlampsio

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:

ahmed-zekry avatar Nov 25 '15 16:11 ahmed-zekry

Awesome thanks!

amberlampsio avatar Nov 25 '15 16:11 amberlampsio

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?
        }

amberlampsio avatar Nov 25 '15 16:11 amberlampsio

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

ahmed-zekry avatar Nov 25 '15 17:11 ahmed-zekry

You're right about that!

amberlampsio avatar Nov 25 '15 17:11 amberlampsio

Thanks, I need to do something like this for both roles and permissions.

mackhankins avatar Feb 04 '16 15:02 mackhankins

https://github.com/mackhankins/roles and https://github.com/sw-double/roles both have that feature now.

mackhankins avatar Feb 25 '16 15:02 mackhankins