Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel factory error "Maximum retries of 10000 reached without finding a unique value" when I use unique Faker method

I have a Unit Seeder with this code in the run method: Unit::factory()->count(10)->create();

And the Unit Factory looks like this:

class UnitFactory extends Factory
{
    protected $model = Unit::class;

    public function definition()
    {
        // $unitUbitactionIds = UnitUbication::pluck('id');
        $testIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
        
        return [
            'unit_ubication_id' => $this->faker->unique()->randomElement($testIds),
            'name' => $this->faker->word()
        ];
    }
}

This thrown an OverflowException: "Maximum retries of 10000 reached without finding a unique value".

If there are 10 Units, and 10 items in the array... Why can't I get one unique id from the array for each Unit?

like image 516
fdr Avatar asked Sep 05 '25 03:09

fdr


1 Answers

You need to use:

$this->faker->unique()->numberBetween(1, 10)

instead of ... ->randomElement($testIds)...

With a small data set, the randomElement() method is different from numberBetween() it randomly generates the same value from your list many times, which is repeated in a loop, which leads to an error in which it is concret reported that the limit of the search for a unique value has been reached.

like image 71
Александр Королёв Avatar answered Sep 07 '25 22:09

Александр Королёв