'How to remove all roles from the user in spatie/laravel-permission

whats the best or the usual way to remove all roles from a user?

I tried

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

Return value of App\User::getStoredRole() must implement interface Spatie\Permission\Contracts\Role, instance of Illuminate\Support\Collection returned


Solution 1:[1]

Use the plain Laravel detach method like so:

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

Solution 2:[2]

I dod it now in this way $user->removeRole($user->roles->first());

Solution 3:[3]

From reading the documentation it clearly says that you can pass a Collection instance to the removeRole so I think you are doing it right.

The assignRole, hasRole, hasAnyRole, hasAllRoles and removeRole functions can accept a string, a \Spatie\Permission\Models\Role object or an \Illuminate\Support\Collection object.

Solution 4:[4]

You can also remove all roles by syncing to an empty array, like so.

$user->syncRoles([]);

I confirmed it works on version 5.8.

Solution 5:[5]

This works fine even on Laravel 7

For Roles: $user->syncRoles([]);

For Permissions: $user->syncPermissions([]);

Solution 6:[6]

From Spatie documentation you can find ther is a way to remove all previous roles and assign new roles with simple

$user->syncRoles($roles);

For reference you can visit this link

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Paras
Solution 2 Smoky
Solution 3 Nikola Gavric
Solution 4
Solution 5
Solution 6 Challenger