Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 8 factory state afterCreating

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?

like image 871
Nebster Avatar asked Oct 28 '20 13:10

Nebster


People also ask

What is default state in Laravel factory?

* 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.

What is a factory in Laravel?

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.

How to create fake data using Faker and factory in Laravel 8?

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.

How do I use state transformation in Laravel?

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.


1 Answers

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) {
        // ...
    });
}
like image 120
Nebster Avatar answered Nov 03 '22 23:11

Nebster