Laravel Factory not calling callback 'afterCreating'

Viewed 1020

I'm trying to modify models after creating them with Factory. I have defined configure() method and within it what I want changed within the model. However, Laravel doesn't call it and it saves the original values which aren't modified. How to fix this?

Here is the configure function within the MealFactory:

public function configure()
{
    return $this->afterCreating(function (Meal $meal) {
        $meal->setTranslation('title', 'hr', 'Croatian translation' . $meal->getId())
            ->setTranslation('title', 'de', 'German translation' . $meal-getId());
    });
}

In table seeder I call it like this:

    $meals = $mealFactory
        ->count(15)
        ->create();
3 Answers

Call $meal->save() at the end of afterCreating callback.

Consider following code;

    return $this->afterCreating(function (Meal $meal) {
        $meal->setTranslation('title', 'hr', 'Croatian translation' . $meal->getId())
            ->setTranslation('title', 'de', 'German translation' . $meal-getId());

        // Save
        $meal->save();
    });

As mentioned by Влад Киевский, configure() is only called from new(), so make sure you are using new() to instantiate the factory class.

// Don't use
$mealFactory = new MealFactory();

// Use instead
$mealFactory = MealFactory::new();
Related