'Laravel Factory not calling callback 'afterCreating'
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();
Solution 1:[1]
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();
Solution 2:[2]
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();
});
Solution 3:[3]
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();
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 | ???? ???????? |
Solution 2 | cednore |
Solution 3 | Karl Hill |