How to get unique values from faker?
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 toUser::count()
, else it will return anOverflowException
error.
Related videos on Youtube
schutte
Updated on June 04, 2022Comments
-
schutte almost 2 years
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.
-
Kamlesh Paul over 3 yearsDoes this answer your question? In Laravel, how do I retrieve a random user_id from the Users table for Model Factory seeding data generation?
-
schutte over 3 years@KamleshPaul it did not returned unique values, no difference from my code above.
-