Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate Faker's random first name and its last name to a full name in Laravel 5

I am trying to use Faker in Laravel 5. Now I need to create some users in my User table, I choose Faker.

I know how to create random firstname, lastname or userName, but I want to concatenate each FN and LN to be username, how can I do that? Here is my codes in seeder file.

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

like image 912
bill dou Avatar asked Oct 29 '15 20:10

bill dou


1 Answers

You would just create the faker firstName and lastName in the foreach loop and then concatenate them for the 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))
        ]);
    }
}

To answer your second question. It depends on your desired email address.

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))
        ]);
    }
}
like image 157
whoacowboy Avatar answered Oct 16 '22 02:10

whoacowboy