5

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

schutte
  • 1,949
  • 7
  • 25
  • 45
  • Does this answer your question? [In Laravel, how do I retrieve a random user\_id from the Users table for Model Factory seeding data generation?](https://stackoverflow.com/questions/44102483/in-laravel-how-do-i-retrieve-a-random-user-id-from-the-users-table-for-model-fa) – Kamlesh Paul Oct 06 '20 at 06:22
  • @KamleshPaul it did not returned **unique** values, no difference from my code above. – schutte Oct 06 '20 at 08:41

2 Answers2

7

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.

tempra
  • 2,455
  • 1
  • 12
  • 27
0

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();
    ...
}
CodingKiwi
  • 676
  • 8
  • 22