13

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?

Nebster
  • 884
  • 1
  • 11
  • 19

2 Answers2

35

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) {
        // ...
    });
}
Nebster
  • 884
  • 1
  • 11
  • 19
  • 1
    I think, this is not an answer of your question. . It should possibly be an edit of your question – STA Oct 28 '20 at 14:18
  • 6
    ^^^ Disagree this is definitely an answer. A helpful one at that judging by the upvotes. I actually didn't realize they answered their own question until I saw your comment. – Nick Jun 16 '21 at 20:35
1

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) {
            //
        });
    }
Najathi
  • 2,529
  • 24
  • 23