Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Factory not calling callback 'afterCreating'

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

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();
like image 970
abelxo47 Avatar asked Oct 27 '25 16:10

abelxo47


2 Answers

According to https://github.com/illuminate/database/blob/master/Eloquent/Factories/Factory.php

method configure called only when method new called, which in current version called only when times is called, so in your case should work using:

$mealFactory
    ->times(15)
    ->create();
like image 135
Влад Киевский Avatar answered Oct 29 '25 06:10

Влад Киевский


If you defined newFactory in your model, make sure it's using Factory::new() and not new Factory

protected static function newFactory(): UserFactory
{
    return UserFactory::new();
}
like image 25
Tofandel Avatar answered Oct 29 '25 06:10

Tofandel