Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Lugi's avatar
Level 21

Factory (Faker) to chose between some strings

What is the easiest way to create factory which could choose between 2 or more options to seed the property ?

For example:

transferStatus could be 'in progress' or 'transferred'.

projectStatus could be 'active', 'completed', 'on hold'.

Should I use array_rand() or does Faker has some method to do this ?

0 likes
5 replies
mstnorris's avatar
Level 55

@Loogey Yes, Faker can help you with this, use randomElement. Create an array and use:

'transferStatus' = $faker->randomElement(['in progress', 'transferred']); // or whatever you want

'projectStatus' = $faker->randomElement(['active', 'completed', 'on hold']);
14 likes
boromake's avatar

What if the value of 'projectStatus' depends on the value of 'transferStatus'? For example if 'tranferStatus' is 'in progress', then 'projectStatus' can only be 'active' or 'completed'. If 'transferStatus' is 'transferred', then 'projectStatus' can only be 'on hold'.

Is there a way to do something like that through Faker?

boromake's avatar

OK I think I found something that works for me. I realized you can just name different configurations of Faker settings for the same Model:

$factory->defineAs(App\User::class, 'admin', function ($faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->email,
        'password' => str_random(10),
        'remember_token' => str_random(10),
        'admin' => true,
    ];
});

And then call whichever one you want:

// Create three App\User instances...
$users = factory(App\User::class, 3)->make();

// Create an App\User "admin" instance...
$user = factory(App\User::class, 'admin')->make();

Please or to participate in this conversation.