How to generate a unique fake email with a custom domain with faker?

Ramy Tamer picture Ramy Tamer · Apr 3, 2017 · Viewed 8k times · Source

I have a laravel application that requires the registered users must use their company email (custom domain).

So how i can i achieve that with faker generators to test it with my model factories ?

Answer

Ramy Tamer picture Ramy Tamer · Apr 3, 2017

You can use a simple trick with php's preg_replace function:

preg_replace('/@example\..*/', '@domain.com', $faker->unique()->safeEmail)

so your laravel model factory might looks like this:

$factory->define(App\User::class, function (Faker\Generator $faker) {
    static $password;
    return [
        'name' => $faker->name,
        'email' => preg_replace('/@example\..*/', '@domain.com', $faker->unique()->safeEmail),
        'password' => $password ?: $password = bcrypt('secret'),
        'avatar' => $faker->imageUrl,
        'remember_token' => str_random(10),
    ];
});