Laravel update factory after creation

Laravel update factory after creation

David Carr

1 min read - 5th Nov, 2022

factories Laravel

Using a Laravel factory to create a user and then update a relationship directly is possible using factory callbacks. Using a configure method you can call afterCreating and afterMaking closures:

 $this->faker->name(),
            'slug'           => Str::slug($this->faker->name()),
            'email'          => $this->faker->email(),
            'password'       => Hash::make('password'),
            'is_active'      => 1,
            'remember_token' => Str::random(10),
        ];
    }

    public function configure()
    {
        return $this->afterCreating(function (User $user) {
            $user->tenant_id = Tenant::factory()->create([
                'owner_id' => $user->id
            ]);
            $user->save();
        });
    }
}

Read more about Factory Callbacks

0 comments
Add a comment

Copyright © 2024 DC Blog - All rights reserved.