phplaravelfakerlaravel-seeding

Laravel faker generate gender from name


What is the optimum way of generating gender using faker, having generated a name so that the gender matches the name

 return [
    'name' => $faker->name,
    'email' => $faker->safeEmail,
    'username' => $faker->userName,
    'phone' => $faker->phoneNumber,
    'gender' => $faker->randomElement(['male', 'female']),//the gender does not match the name as it is.
    'address' => $faker->address,
    'dob' => $faker->date($format = 'Y-m-d', $max = 'now'),
    'password' => bcrypt('secret')
    ];

Solution

  • Looking at the documentation and an issue raised on the their Github issues section, your solution seems to be the best. Some methods allow you to specify the gender for a name so you could do like this:

    $gender = $faker->randomElement(['male', 'female']);
    
    return [
        'name' => $faker->name($gender),
        'email' => $faker->safeEmail,
        'username' => $faker->userName,
        'phone' => $faker->phoneNumber,
        'gender' => $gender,
        'address' => $faker->address,
        'dob' => $faker->date($format = 'Y-m-d', $max = 'now'),
        'password' => bcrypt('secret')
    ];
    

    Hopefully this fits your requirement.