Lovepreet Singh
Lovepreet Singh

Reputation: 1

How to assign only one role to the user using Spatie?

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:

  1. Laravel version: 9
  2. Spatie Laravel Permissions package version: 5.5.2
  3. laravel-json-api version: v4.0.0
  4. Code snippet of current user role assignment logic
$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

Answers (1)

bilal ehsan
bilal ehsan

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

Related Questions