Search code examples
phplaravellaravel-5faker

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


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 ?


Solution

  • 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),
        ];
    });