Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
    ];
like image 498
Morris Mukiri Avatar asked Mar 31 '17 10:03

Morris Mukiri


3 Answers

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.

like image 83
James Avatar answered Nov 16 '22 04:11

James


  1. The method randomElements is gonna return an array with one single element, so if you want to get 'female' or 'male', don't forget to add at the end of the first line this: [0]. You need the first element (index 0) of the resulting array (that only has one element).

     $gender = $faker->randomElements(['male', 'female'])[0];
    
  2. One more thing. In order to obtain exactly what you want, you need to use firstName instead of name. This way the first name will be according to the gender. Do it this way:

     return [
         'name' => $faker->firstName($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')
     ];
    
  3. One last thing: If you use 'Male' and 'Female', instead of 'male' and 'female', this is NOT gonna work!!

like image 38
Reinier Garcia Avatar answered Nov 16 '22 03:11

Reinier Garcia


to do it without additional variable, do it like this

return [
  'gender' => $faker->randomElements(['male', 'female']),
  'name' => $faker->name(function (array $user) {return $user['gender'];})
]

hope it helps

like image 43
Bang Fady Avatar answered Nov 16 '22 04:11

Bang Fady