Search code examples
laravellaravel-7factories

Why i can't create fake data with faker when i use the unique method


I try to create fake data for a todo app project so i use factory for to do that

i use on the for the category Model this :

$factory->define(Category::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'order' => $faker->unique()->randomDigitNotNull,
    ];
});

and when i use tinker everything works perfectly but when i to the task model

$factory->define(Task::class, function (Faker $faker) {
    return [
        'category_id' => $faker->numberBetween($min = 1, $max = 6),
        'name' => $faker->name,
        'description' => $faker->text($maxNbChars = 200),
        'satus' => $faker->boolean,
        'expired_at' => $faker->dateTime($max = 'now'),
        'order' => $faker->unique(true)->numberBetween(1, 50),

    ];
});

i receive an error "OverflowException with message 'Maximum retries of 10000 reached without finding a unique value'" and i don't know why its not working


Solution

  • This works

    for ($i = 1; $i < 10; $i++) {
        $faker->unique()->randomDigitNotNull;
    }
    

    When you increase 10 to any value(12, 15, 25); it is going to give an exception because of the implementation of randomDigitNotNull method.

    public static function randomDigitNotNull()
    {
        return mt_rand(1, 9);
    }
    

    Since you are saying unique and the method will return you a value in that range [1,9]. if your loop iterates more than 9 times than at least one value will not be unique.