Search code examples
laravellaravel-seedinglaravel-factory

How to use a custom list of values for a Laravel factory, maintaing order and still using the Faker facade?


I have a list of names $names = ['Adam','Beth,'Chancie','Dale', 'Edward']; etc.. That I want to use in a Laravel factory, or seeder, I don't know which one.

Basically, I still want to use the Faker functionality for everything else, but provide my own custom list of names in the order they are listed in the array.

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => MY_CUSTOM_LIST_NAME,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        'remember_token' => Str::random(10),
    ];
});

Solution

  • You could always create a private method which you call as you loop over each name in your array.

    $factory->define(User::class, function (Faker $faker) {
    
        foreach($name in $names) {
            $this->customFakerMethod($name);
            // your logic here ...
        }
    });
    

    This function just takes the name as a parameter.

    private function customFakerMethod($name)
    {
        return [
            'name' => $name,
            'email' => $faker->unique()->safeEmail,
            'email_verified_at' => now(),
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
        ];
    }
    
    

    So your users will be created in the order that you wish.