Home » Php » php – Laravel faker generate gender from name

php – Laravel faker generate gender from name

Posted by: admin July 12, 2020 Leave a comment

Questions:

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')
    ];
How to&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.

Answer:

  1. The method randomElements is gonna return an array with one single element, so if you really want to get ‘female’ o ‘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!!

Answer:

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

Answer:

Actually all answers did not really work for me. It returned female or male only.
I had almost the same issue. I needed a random element out of three genders 👍😀. It always gave me this error message:

 Illuminate\Database\QueryException  : Array to string conversion (SQL: insert 
 into `users` (`name`, `gender`, `email`, `admin`, `author`, `password`, 
 `remember_token`) values (Margaret Robel I, male, [email protected], 1, 0, 
 dummylogin, gwKdVN7zYv))

 at /Users/mangrove/Desktop/php-workspace/laravel- 
 mangrove/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
 660|         // If an exception occurs when attempting to run a query, we'll 
 format the error
 661|         // message to include the bindings with SQL, which will make this 
 exception a
 662|         // lot more helpful to the developer instead of just the 
 database's errors.
 663|         catch (Exception $e) {
 > 664|             throw new QueryException(
 665|                 $query, $this->prepareBindings($bindings), $e
 666|             );
 667|         }
 668| 

 Exception trace:

 1   ErrorException::("Array to string conversion")
 /Users/mangrove/Desktop/php-workspace/laravel- 

 mangrove/vendor/laravel/framework/src/Illuminate/Database/
 MySqlConnection.php:80

 2   PDOStatement::bindValue()
 /Users/mangrove/Desktop/php-workspace/laravel- 

 mangrove/vendor/laravel/framework/src/Illuminate/
 Database/MySqlConnection.php:80

After a look at the documentation for Faker v.1.8.0

This worked for me:

public function run()
{
  $faker = Faker::create();
  foreach(range(1,10) as $index){

    // Returns always random genders according to the name, inclusive mixed !!
    $gender = $faker->randomElement($array = array('male','female','mixed'));

    DB::table('users')->insert([
          'name' => $faker->name($gender),   
          'gender' => $gender,           
          'email' => $faker->unique()->safeEmail,
          'admin' => $faker->numberBetween($min = 0, $max = 1),
          'author'=> $faker->numberBetween($min = 0, $max = 1),
          'password' => 'dummylogin',
          'remember_token' => str_random(10),
    ]);
  }
}

It turns out mixed genders will always have different names, because you can 
be either way 😄⚧