In a UserFactory, I need to write a state method that attaches the user being created (or created) to a many to many "role" object

In a UserFactory, I need to write a state method that attaches the user being created (or created) to a many to many "role" object

Problem Description:

I would want to write something like this:

class UserFactory extends Factory
{

   public function withRoles(array $roles) {
        $factory->state(function (array $attributes) use ($roles)  {
                     $user = User::find($attributes['id']);
                     $roles = Role::whereIn('title', $roles)->get();
                     $user->roles()->attach($roles);
    
                     return $user;
        });
   }

Unfortunately, id is not available in this $attributes nor, I guess, in the state methods of a factory.

What could I do to solve this problem?

Solution – 1

You can use a callback function in the configure function of the UserFactory:

class UserFactory extends Factory
{
    /**
     * Configure the model factory.
     *
     * @return $this
     */
    public function configure()
    {
        return $this->afterMaking(function (User $user) {
            
        })->afterCreating(function (User $user) {
            //
        });
    }
 
    // ...
}

This would do it every time you use the create / make UserFactory functions.

Alternatively you may use the built in ->hasAttached() or ->has() method e.g.

$user = User::factory()
            ->count(3)
            ->has($roles)
            ->create();

This is all outlined pretty well in the Laravel documentation for factories: https://laravel.com/docs/9.x/eloquent-factories#factory-states

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject