Smoky
Smoky

Reputation: 141

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

Upvotes: 4

Views: 23194

Answers (6)

Ali
Ali

Reputation: 171

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

Upvotes: 0

Leonard203
Leonard203

Reputation: 61

This works fine even on Laravel 7

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

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

Upvotes: 0

KvdLingen
KvdLingen

Reputation: 1344

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

$user->syncRoles([]);

I confirmed it works on version 5.8.

Upvotes: 6

Paras
Paras

Reputation: 9465

Use the plain Laravel detach method like so:

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

Upvotes: 13

Smoky
Smoky

Reputation: 141

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

Upvotes: 1

Nikola Gavric
Nikola Gavric

Reputation: 3543

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.

Upvotes: 1

Related Questions