I am facing an issue in setting up the Spite Permissions within my Laravel App
I have followed the following guide https://medium.com/@miladev95/step-by-step-guide-to-user-role-and-permission-tutorial-in-laravel-10-1fecdabfdea0 and I get the following error when running the db:seed
BadMethodCallException
Call to undefined method App\Models\Role::givePermissionTo()
at vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php:67
63▕ * @throws \BadMethodCallException
64▕ */
65▕ protected static function throwBadMethodCallException($method)
66▕ {
➜ 67▕ throw new BadMethodCallException(sprintf(
68▕ 'Call to undefined method %s::%s()', static::class, $method
69▕ ));
70▕ }
71▕ }
i Bad Method Call: Did you mean App\Models\Role::getRelation() ?
1 vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php:36
Illuminate\Database\Eloquent\Model::throwBadMethodCallException("givePermissionTo")
2 vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php:2334
Illuminate\Database\Eloquent\Model::forwardCallTo(Object(Illuminate\Database\Eloquent\Builder), "givePermissionTo")
This is my User Model
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
use HasRoles;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
public function roles()
{
return $this->belongsToMany(Role::class);
}
public function permissions()
{
return $this->belongsToMany(Permission::class);
}
}
I ensured I had the use HasRole within the User Model as required.
My RoleSeeder is as follows:
namespace Database\Seeders;
use App\Models\Role;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class RoleSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
//
$adminRole = Role::create(['guard_name' => 'super-admin', 'name' => 'super-admin']);
$userRole = Role::create(['guard_name' => 'user', 'name' => 'user']);
$adminRole->givePermissionTo('all');
}
}
Any help would be great
if you are going to use your own Role model instead of package's model, you should extend your model with package model
use Spatie\Permission\Models\Role as SpatieRole;
class Role extends SpatieRole{
}
then in permission.php config file u need to change the model that package using.
return [
'models' => [
'role' => \App\Models\Role::class,
]
.....
];