How to get unique values from faker?

schutte picture schutte · Oct 6, 2020 · Viewed 11.4k times · Source

I would like to ask how to generate unique value from faker?

I know this is a familiar question actually, you may put some duplicate links e.g. link 1, link 2 but unfortunately, these links does not answer my problem.


Here is my code below. I tried unique(true) but same result.

return [
    'user_id' => $this->faker->unique()->numberBetween(1, 10),
    //more code here
];

Below is the result that I got. As you can see there are lots of duplicate "5" inserted.

enter image description here

Answer

The factory is the real issue here not the faker. Calling of factory I mean.

Let's say you have User and User_Information model for example since you have not mention any models in your question above.


I assume you call the factory like below in which it creates a model one by one separately up to 10 that makes unique() of faker useless.

\App\Models\User_Information::factory()->create(10);

My solution to this problem is to use a loop to make unique() functional.

$max = 10;
for($c=1; $c<=$max; $c++) {
    \App\Models\User_Information::factory()->create();
}

NOTE: $max must not be greater to User::count(), else it will return an OverflowException error.