简体   繁体   中英

Laravel: How can i generate two unique seeds in my laravel faker

I want to create two unique users in my faker. I wanna know the right way of doing it.

$factory->define(App\User::class, function (Faker\Generator $faker) {
    static $password;

    return [
      {
        'name' => "Person 1",
        'email' => "person1@gmail.com",
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => str_random(10),
        'role' => 'super',
      },
      {
        'name' => "Person 2",
        'email' => "person2@gmail.com",
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => str_random(10),
        'role' => 'admin',
      },
    ];
});

This code solved my problem

$factory->define(App\User::class, function (Faker\Generator $faker) {
static $password;

return [

    'name' => $faker->unique()->randomElement($array = array ('Person1','Person2')),
    'email' => $faker->unique()->randomElement($array = array ('p1@gmail.com','p2@gmail.com')),
    'password' => $password ?: $password = bcrypt('secret'),
    'remember_token' => str_random(10),
    'role' => $faker->unique()->randomElement($array = array ('super','admin')),
];
});

This code solved my problem:

do {
        $uniqueName = $faker->name;
        $uniqueEmail = $faker->unique()->safeEmail;
    } while (User::where([
            'name' => $uniqueName,
            'email' => $uniqueEmail,
        ])
            ->count()
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM