0

i have 2 tables user and roles, i want to create a user factory so that i add an admin role for that user created. I have the user table with (id,name,...,age ) and the roles table with (id, user_id and role_name). i want to make a factory that creates a user and gives him the role of an admin. (remember the role is accessed through the hasmany relationship from the user model ) how can i achieve this.

        public function definition(): array
        {
            return [
                'name' => fake()->name(),
                'email' => fake()->unique()->safeEmail(),
                'email_verified_at' => now(),
                'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
                'remember_token' => Str::random(10),
            ];
        }

        /**
         * Indicate that the model's email address should be unverified.
         */
        public function unverified(): static
        {
            return $this->state(fn (array $attributes) => [
                'email_verified_at' => null,
            ]);
        }
        public function configure()
        {
            return $this->afterCreating(function (User $user) {
                // Create and assign a role to the user
                $role = Role::factory()->create();
                $user->roles()->attach($role);
            });
        }

1 Answers1

0

In your database seeder you could do:

User::factory()->create(10)->each(function ($user) {
   $user->roles()->attach(1);
});

Most of the time keeping your factory simple is better, this way you can use it for something else later if needed, any extra logic can be done on the seeder.

If you do really want it in the factory you could do something like:

(user factory class)
public function withAdminRole()
{
   return $this->hasAttached(
       Role::factory()->create([
        'name' => 'admin',
        'label' => 'Administrator',
        ), 'roles');
}

(in a way that suits your situation)

and call it in the seeder like this:

User::factory()->withAdminRole()->create(10);
Jordy
  • 73
  • 6