I'm creating "Foo" models using a Laravel 10 factory. I want each model Foo to have a belongsTo relationship to different random already existing model "Bar". There is no factory for Bar and I want to minimize the number of database queries. For each new Foo, a random Bar should be picked, I don't want to use the same Bar for every Foo.
I found a simple solution but it required to fetch all the Bar models for every created Foo and I wanted to avoid unnecessary queries.
The only way I found is to use states with the Bar models collection :
$bars = Bar::all();
Foo::factory()
->count(3)
->state(function () use ($bars) {
return ['bar_id' => $bars->random()->id];
})
Isn't there a simpler way to do it?
you can solve this issue by generating random
bar_idvalues within the factory itself. Here's how you can do it: