Laravel-permission: How can i remove all user roles with a line code?

Created on 19 Oct 2019  路  1Comment  路  Source: spatie/laravel-permission

Hello,

My code works correctly when like this,

$user->removeRole($user->roles->first());

But I am trying remove multiple roles like this;

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

and Laravel throwing this error message '
Return value of AppUser::getStoredRole() must implement interface SpatiePermissionContractsRole, instance of IlluminateDatabaseEloquentCollection returned'

isnt there any collection support for remove role action ?

support

Most helpful comment

isnt there any collection support for remove role action ?

No, there are no plans to support passing a collection to removeRole.

There are 3 alternatives:

  1. Remove roles 1-by-1 as you're doing.

  2. Given that in most cases of removing "all" roles you probably are removing in order to assign different roles, you could use syncRoles to remove all and attach a new set and still reset the cache appropriately all in one command:
    https://github.com/spatie/laravel-permission/blob/e3821559c69b2b1ea8fdd967fa89ba13a01ead78/src/Traits/HasRoles.php#L142-L170

  3. You could just manually call $user->roles()->detach() and then either assign a new role immediately so the cache gets updated automatically or manually call $user-> forgetCachedPermissions().

>All comments

isnt there any collection support for remove role action ?

No, there are no plans to support passing a collection to removeRole.

There are 3 alternatives:

  1. Remove roles 1-by-1 as you're doing.

  2. Given that in most cases of removing "all" roles you probably are removing in order to assign different roles, you could use syncRoles to remove all and attach a new set and still reset the cache appropriately all in one command:
    https://github.com/spatie/laravel-permission/blob/e3821559c69b2b1ea8fdd967fa89ba13a01ead78/src/Traits/HasRoles.php#L142-L170

  3. You could just manually call $user->roles()->detach() and then either assign a new role immediately so the cache gets updated automatically or manually call $user-> forgetCachedPermissions().

Was this page helpful?
0 / 5 - 0 ratings