Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Laravel factory random from array
    Laravel factories Faker library random values $faker->randomElement $faker->randomKey Laravel testing generating test data


Laravel factory random from array


To generate a random value from an array in a Laravel factory, you can use the `$faker->randomElement()` method provided by the Faker library.

Here's an example of how you can do this:

php
// database/factories/UserFactory.php
$factory->define(App\User::class, function (Faker\Generator $faker) {
    $userTypes = ['admin', 'editor', 'subscriber'];

    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
        'remember_token' => Str::random(10),
        'type' => $faker->randomElement($userTypes),
    ];
});

In this example, we define an array of user types (`'admin'`, `'editor'`, `'subscriber'`) and use the `$faker->randomElement()` method to randomly select one of these values for the `'type'` attribute of the `User` model.

You can also use this approach to generate random values from an array for other attributes, such as statuses, roles, or any other enumerated values.

Another option is to use the `$faker->randomKey()` method, which selects a random key from the provided array:

php
$userTypes = ['admin' => 1, 'editor' => 2, 'subscriber' => 3];

return [
    'type' => $faker->randomKey($userTypes),
];

This approach is useful if you want to generate a random key from an associative array, where the keys represent the actual values you want to use.

By using the Faker library's random selection methods, you can easily generate realistic and varied test data for your Laravel applications.

Citations:
[1] https://stackoverflow.com/questions/44350793/random-select-value-on-array-factory-laravel
[2] https://laracasts.com/discuss/channels/eloquent/laravel-factory-faker-generate-exact-array-value
[3] https://laraveldaily.com/tip/factory-callbacks
[4] https://laravel.com/docs/7.x/database-testing
[5] https://laravel.io/forum/how-do-i-make-a-factory-that-creates-proper-random-titles