Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lukeboy_2002's avatar

UserFactory with Spatie Permission

Hi,

I use to use the default UserFactory to seed my database with Users. Now I want to die each user te role as User.

For my admin user I have created a separate AdminSeeder that not used the factory

$user = User::create([
            'username' => 'admin',
            'email' => '[email protected]',
            'email_verified_at' => now(),
            'password' => Hash::make('adminadmin'),
            'remember_token' => Str::random(10),
        ]);

        //generate image
        $username = get_initials($user->username);
        $id = $user->id.'.png';
        $path = '/profile-photos/';
        $imagePath = create_avatar($username, $id, $path);

        //save image
        $user->profile_photo_path = $imagePath;
        $user->save();

        $role = Role::select('id')->where('name', 'admin')->first();

        $user->roles()->attach($role);

How Can I assign a Role to a User in the Userfactory or in de DatabaseSeeder

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To assign a role to a user in the UserFactory or DatabaseSeeder using the Spatie Permission package, you can follow these steps:

  1. Update the UserFactory to assign a role to each user.
  2. 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

  1. UserFactory:

    • The configure method 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.
  2. 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.

2 likes

Please or to participate in this conversation.