Reputation: 1
I'm working with the Spatie Laravel Permissions package and I want to assign just one role to a user. However, when i try to update the role of the user, rather then overwriting the assigned role, it assign one more role to the user. Can someone please guide me on how to assign only one role to a user using Spatie?
Here are the details of my current setup:
$user = User::find(auth()->id());
$role = Role::find($role_id);
$user->assignRole($role->name);
I have find a method,first we can remove the assigned roles and then assign the updated role. Like,
$user = User::find(auth()->id());
$getroles = $user->getRoleNames();
foreach($getroles as $getrole){
$user->removeRole($getrole);
};
$role = Role::find($role_id);
$user->assignRole($role->name);
Do we have any better way to achieve this?
Upvotes: -1
Views: 2135
Reputation: 109
To assign just one role to a user using the Spatie Laravel Permissions package, you can use the syncRoles method instead of the assignRole method. The syncRoles method will replace any existing roles with the new roles you specify.
// Find the user you want to assign the role to
$user = User::find($userId);
// Get the role you want to assign
$role = Role::where('name', 'admin')->first();
// Assign the role using syncRoles
$user->syncRoles($role);
Upvotes: 0