'There is no role named `admin`. laravel
i use this package :
code :
$user=User::find(2);
$user->assignRole('admin');
and when i assign admin role to user I'm dealing with this error
There is no role named
admin
.Spatie\Permission\Exceptions\RoleDoesNotExist
this is my default guard in auth.php :
<?php
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
this is my roles table :
this is my role_has_permission table
and this is my permission table :
Solution 1:[1]
just add this protected property to your user model(or whatever model you are using for assigning permissions and roles).
protected $guard_name = 'api';
Solution 2:[2]
Add this to your user model
use Spatie\Permission\Traits\HasRoles;
and in a user model class
use HasRoles;
Here is a reference
Solution 3:[3]
Add one of the following to your User
model:
public $guard_name = 'api';
Or:
public function guardName()
{
return 'api';
}
Solution 4:[4]
As a convention it's best to do configurable things in the config file.
The problem with your code is the order of arranging your guards, just re-arrange as seen below.
<?php
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
...
Once this is done, you don’t need to add protected $guard_name = 'api';
to your User model, ensure to run php artisan config:clear
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 | TEFO |
Solution 2 | |
Solution 3 | Popsyjunior |
Solution 4 | Adedoyin Akande |