Laravel 7 factories had method afterCreatingState() where you could define what should happen after Model with specific state was saved into database.
$factory->afterCreatingState(App\User::class, 'active', function ($user, $faker) {
// ...
});
Laravel 8 factories don't have this method, instead there is only general afterCreating().
public function configure()
{
return $this->afterCreating(function (User $user) {
//
});
}
How to achieve this behavior?
* Define the model's default state. As you can see, in their most basic form, factories are classes that extend Laravel's base factory class and define a definition method. The definition method returns the default set of attribute values that should be applied when creating a model using the factory.
This factory is included with all new Laravel applications and contains the following factory definition: * Define the model's default state. As you can see, in their most basic form, factories are classes that extend Laravel's base factory class and define a definition method.
Create Fake Data using Faker and Factory in Laravel 8 1 Install Laravel 8 App 2 Configure Database with App 3 Create Model and Migration 4 Create Factory Class. After that, open PostFactory.php file, which is found inside database/factories/ directory. 5 Run tinker, Factory Command. Now, visit localhost/phpmyadmin and check database posts table.
State transformation methods typically call the state method provided by Laravel's base factory class. The state method accepts a closure which will receive the array of raw attributes defined for the factory and should return an array of attributes to modify: * Indicate that the user is suspended.
It is possible to define this behavior right in the state definition method.
public function active()
{
return $this->state(function (array $attributes) {
return [
'active' => true,
];
})->afterCreating(function (User $user) {
// ...
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With