4

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?

fdr
  • 41
  • 1
  • 2
  • 1
    ` $this->faker->unique(true)->numberBetween(1,10),` try this – Zahid Hassan Shaikot Jan 25 '22 at 03:42
  • Every instance of the factory would have a new faker instance and therefore unique would be usesless, would it not? – user3532758 Jan 25 '22 at 03:44
  • 1
    or you can get id 'unit_ubication_id' =>UnitUbication::inRandomOrder()->first()->id, – Zahid Hassan Shaikot Jan 25 '22 at 03:45
  • 1
    Random order wouldnt give the unique id. Ideally, for testing purposes, I would create a new UnitUbication, ensuring uniqueness. Otherwise this question has already been answered here: https://stackoverflow.com/questions/64220203/how-to-get-unique-values-from-faker – user3532758 Jan 25 '22 at 03:48
  • Thank you Zahid Hassan Shaikot, using the solution $this->faker->unique(true) works – Two Aug 04 '22 at 03:11

1 Answers1

0

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.