To assign a role to a user in the UserFactory or DatabaseSeeder using the Spatie Permission package, you can follow these steps:
-
Update the
UserFactoryto assign a role to each user. - Ensure the roles are created before seeding users.
Here's how you can do it:
Step 1: Update the UserFactory
First, make sure your UserFactory is set up to create users. Then, you can modify it to assign a role to each user.
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
class UserFactory extends Factory
{
protected $model = User::class;
public function definition()
{
return [
'username' => $this->faker->userName,
'email' => $this->faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => Hash::make('password'), // password
'remember_token' => Str::random(10),
];
}
public function configure()
{
return $this->afterCreating(function (User $user) {
$role = Role::firstOrCreate(['name' => 'user']);
$user->assignRole($role);
});
}
}
Step 2: Update the DatabaseSeeder
Ensure that roles are created before seeding users. You can do this in the DatabaseSeeder.
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use App\Models\User;
class DatabaseSeeder extends Seeder
{
public function run()
{
// Create roles
Role::firstOrCreate(['name' => 'admin']);
Role::firstOrCreate(['name' => 'user']);
// Create admin user
$admin = User::create([
'username' => 'admin',
'email' => '[email protected]',
'email_verified_at' => now(),
'password' => Hash::make('adminadmin'),
'remember_token' => Str::random(10),
]);
// Generate and save profile photo
$username = get_initials($admin->username);
$id = $admin->id . '.png';
$path = '/profile-photos/';
$imagePath = create_avatar($username, $id, $path);
$admin->profile_photo_path = $imagePath;
$admin->save();
// Assign admin role
$admin->assignRole('admin');
// Seed users with factory
User::factory(10)->create();
}
}
Explanation
-
UserFactory:
- The
configuremethod is used to assign the 'user' role to each user after they are created. -
Role::firstOrCreate(['name' => 'user'])ensures that the role exists before assigning it.
- The
-
DatabaseSeeder:
- Roles are created before seeding users to ensure they are available.
- An admin user is created manually and assigned the 'admin' role.
- The
User::factory(10)->create();line seeds 10 users, each of which will be assigned the 'user' role by the factory.
This setup ensures that each user created by the factory is assigned the 'user' role, and the admin user is assigned the 'admin' role.