I'm relatively new to Laravel and I'm try to learn spatie/laravel-permission. I'm using Laravel 10. I'm trying to seed my database with roles and a user.
I'm getting this error:
Spatie\Permission\Exceptions\RoleDoesNotExist
There is no role named admin.
Here is my code. As you can see in the RoleSeeder I do create an admin role. I also have the HasRoles trait in the User model. I'm not sure what I'm doing wrong. Any help would be greatly appreciated.
RoleSeeder.php
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
class RoleSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
Role::create(['name' => 'super admin', 'team_id' => 1, 'guard_name' => 'web']);
Role::create(['name' => 'admin', 'team_id' => 1, 'guard_name' => 'web']);
Role::create(['name' => 'user', 'team_id' => 1, 'guard_name' => 'web']);
}
}
AdminSeeder.php
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class AdminSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$user = User::create( [
'name' => 'admin',
'email' => 'admin@gmail.com',
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
]);
$user->assignRole('admin');
}
}
DatabaseSeeder.php
<?php
namespace Database\Seeders;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
$this->call([RoleSeeder::class, AdminSeeder::class]);
}
}
User.php
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
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, HasRoles;
protected $guard_name = 'web';
/**
* 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',
];
}