How to get unique values from faker?

30.6k Views Asked by At

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

2

There are 2 best solutions below

0
On BEST 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.

0
On

In my case I had a setup like this

class DomainFactory extends Factory {
    protected $model = Domain::class;

    public function definition() {
       return ['name' => $this->faker->unique()->domainWord()]
    }
}
// Seeder
for ($i = 0; $i < 10; $i++) {
    $domain = Domain::factory()->create();
    ...
}

Which did NOT generate unique values for name because I basically create a new factory and with that a new faker in each loop run. I had to pull the factory out of the loop:

// Seeder
$factory = Domain::factory();

for ($i = 0; $i < 10; $i++) {
    $domain = $factory->create();
    ...
}