Ronnie
Ronnie

Reputation: 11198

Add user to existing role in laravel

I am using https://github.com/romanbican/roles to manage user roles. I am trying to set a user's role to an existing role.

I can create a new role via:

$role = Role::create([
  'name' => 'Admin',
  'slug' => 'admin'
]);

$user = User::find($id)->attachRole($role);

which works fine. The problem is setting the role to an existing role. There is the attachRole method which accepts an id. I assumed the id of the role. It'd be nice if I can just do attachRole('admin');

It isn't very clear how to do this in the docs. I've tried simply creating the role again but I get a duplicate role error, as expected. Sorry if this is a noob question, I just started with L5 yesterday.

Upvotes: 0

Views: 594

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152880

I don't know the package but you should be able to retrieve the role model and use that:

$role = Role::where('slug', 'admin')->first();
$user = User::find($id)
if($role && $user){
    $user->attachRole($role);
}
else {
    // either role or user not found
}

Upvotes: 1

Related Questions