How to add unique email in Laravel Faker

How to add unique email in Laravel Faker

Posted on:August 30, 2019 at 10:00 AM

Imagine that, you have a UserFactory in laravel project where the email address is unique. In general, you can easily add generate an email with faker like this way-

<?php

use Faker\Generator as Faker;

$factory->define(App\User::class, function (Faker $faker) {
    return [
        'username' => $faker->name,
        'email' => $faker->email,
        'remember_token' => str_random(60),
        'password' => $faker->sha1, // secret
        'remember_token' => str_random(10)
    ];
});

But this line of code 'email' => $faker->email will generate an email for you that doesn’t make sure whether it is unique or not. In that case, your testing can be a failure for that.

So, to address this issue, you can use unique() method. It will be like this-

'email' => $faker->unique()->email

The overall code will be like this-

<?php

use Faker\Generator as Faker;

$factory->define(App\User::class, function (Faker $faker) {
    return [
        'username' => $faker->name,
        'email' => $faker->unique()->email,
        'remember_token' => str_random(60),
        'password' => $faker->sha1, // secret
        'remember_token' => str_random(10)
    ];
});

Hope this small tip will be helpful for you.

Thank you.