如何将Faker的随机名和它的姓名连接到Laravel 5中的全名

时间:2015-10-29 20:41:06

标签: laravel random faker

我正在尝试在Laravel 5中使用Faker。现在我需要在User表中创建一些用户,我选择Faker。

我知道如何创建随机的firstname,lastname或userName,但我想将每个FN和LN连接为用户名,我该怎么做?这是我在播种文件中的代码。

public function run()
{
    $faker = Faker::create();

    foreach(range(1, 10) as $index) {
        User::create([
            'first_name'     => $faker->firstName($gender = null|'male'|'female'),
            'last_name'     => $faker->lastName,
            'username'     => $faker->userName(),
            'email'     => $faker->email,
            'password'     => bcrypt($faker->password(6))
        ]);
    }
}

image of seeder content

1 个答案:

答案 0 :(得分:4)

您只需在foreach循环中创建faker firstNamelastName,然后将其连接到username

public function run()
{
    $faker = Faker::create();

    foreach(range(1, 10) as $index) {
        $firstName = $faker->firstName;
        $lastName = $faker->lastName;
        User::create([
            'first_name'     => $firstName,
            'last_name'     => $lastName,
            'username'     => $firstName.$lastName,
            'email'     => $faker->email,
            'password'     => bcrypt($faker->password(6))
        ]);
    }
}

回答你的第二个问题。这取决于您所需的电子邮件地址。

public function run()
{
    $faker = Faker::create();

    foreach(range(1, 10) as $index) {
        $firstName = $faker->firstName;
        $lastName = $faker->lastName;
        $username = $firstName.$lastName;

        // username @ specific url
        $email = $username.'@exampple.ca';

        // first initial last name @ specific url
        $email = $firstName[0].$lastName.'@exampple.ca';

        // username @  random email safe url
        $email = $username.'@'.$faker->safeEmailDomain;

        // first initial last name @ random email safe url
        $email = $firstName[0].$lastName.'@'.$faker->safeEmailDomain;

        User::create([
            'first_name'     => $firstName,
            'last_name'     => $lastName,
            'username'     => $username,
            'email'     => $email,
            'password'     => bcrypt($faker->password(6))
        ]);
    }
}