'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?



Solution 1:[1]

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) {
        // ...
    });
}

Solution 2:[2]

after crating - state

public function active()
    {
        return $this->state([
            'active' => true,
        ])->afterCreating(function (Article $user) {
            // ...
        });
    }

Configure the model factory.

    public function configure()
    {
        return $this->afterCreating(function (User $user) {
            //
        });
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nebster
Solution 2 Najathi