Laravel factory: recycle method not randomize input collection

1k Views Asked by At

It says in the documentation that "The recycle method also accepts a collection of existing models. When a collection is provided to the recycle method, a random model from the collection will be chosen when the factory needs a model of that type:"

But whenever I use available collection and use recycle method, it will always return the last of the collection. this is my seed code

Product::factory()
    ->count(10)
    ->recycle(AgeGroupMarketplace::all())
    ->state(['age_group_marketplace_id' => AgeGroupMarketplace::factory()])
    ->create();

It will always seed table product with age_group_marketplace_id = last age group id in my age group table. I wonder is this a bug or I do something wrong in my code?

I expecting age_group_marketplace_id column to be random based on the existing collection

1

There are 1 best solutions below

0
On

I have the following code and it works, it takes a random Zone and Person for every property. Maybe you have an outdated-bugged version of the Laravel framework, trying updating your packages with composer update might work

$zones = Zone::where('city_id', 2)->get();
    
$people = Person::factory()->count(10)->create();
    
Property::factory()
            ->count(50)
            ->recycle($zones)
            ->recycle($people)
            ->state(['zone_id' => Zone::factory(), 'landlord_id' => Person::factory()])
            ->create();

Retrieving your models using ->get() instead of ->all() would produce any change, maybe?