Using a Laravel factory, how to add different random relationships from a model collection?

143 views Asked by At

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?

1

There are 1 answers

0
Mehdi Jahromi On

you can solve this issue by generating random bar_id values within the factory itself. Here's how you can do it:

Foo::factory()
    ->count(3)
    ->create([
        'bar_id' => function () {
            return Bar::inRandomOrder()->first()->id;
        },
    ]);