Repository navigation
Is there a good way to utilize configure() function when you need to conditionally add items to a factory in an afterCreating hook #39195
Replies: 2 comments 5 replies
|
I also had to proceed like you did, using a static prop to transfer pending data that are meant to be used to attach relationships (in the I wished it would have been possible to stack multiple calls to |
|
hi roni actually there is no need for such a complex structure and static variables you can define hooks specifically within a state in laravel factories in your case instead of dealing with static variables you can return the aftercreating hook directly inside the withfakeimage method this way you wont have issues with parallel testing and your code will be much cleaner the following usage should be more than enough /**
* indicate that the review has fake images
*
* @param string|null $name
* @return \illuminate\database\eloquent\factories\factory
*/
public function withfakeimage(?string $name = null): self
{
return $this->aftercreating(function (review $review) use ($name) {
$count = $this->faker->numberbetween(1, 3);
for ($i = 0; $i < $count; $i++) {
$image = uploadedfile::fake()->image(($name ?? $this->faker->word) . '.jpg');
$review->addmedia($image)->tomediacollection('review_media');
}
});
}this way the image upload process only runs when you add the withfakeimage() method to the chain even if the factory object is regenerated the aftercreating hook remains bound to that instance you will completely get rid of static variable tracking and that complex hashing process your code will be fully compliant with laravel standards good luck man |
Uh oh!
There was an error while loading. Please reload this page.
This was a hacky solution but it worked, in a way that wouldn't interfere with parallel testing. It's terrible and there must be a better solution...
I was given a factory that was a bit messed up and slow because it was always utilizing $this->faker->image which causes a download. However, for testing, images are only required for a tiny fraction of tests, so it should be isolated in a state, rather than being the default action.
However, I was unable to find a way to get the state to manipulate any class variables since the object is regenerated. Instead i added some static class variables and a naive hash to determine if the configure should fire. It's horrible but it gets the job done.
I ideally I was hoping for the new instance to clone the private/protected variables on the class which we could manipulate with public facing methods to avoid this dance. Is there a better solution? If there isn't, I could try to put together a PR if it would be welcome or happily assist someone else who wanted to run with this.
Thanks.
All reactions