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

xingfucoder's avatar

Enum field population with Faker and Factories

Hi, I need to populate an enum field with three values enum('low', 'medium', 'hight'). I'm using Faker and Factories in Laravel 5.3, how can I do to populate using the Factory with one of those values?

Thanks.

0 likes
10 replies
xingfucoder's avatar

I answer it and give anyone needs the same sample code:

$factory->define(ClassName::class, function (Faker\Generator $faker) {
    //Array values
    $arrayValues = ['low', 'medium', 'hight'];

    return [
        'name' => $faker->name,
        'damage' => $arrayValues[rand(0,2)]
    ];
});

That sample code is placed in the ModelFactory.php file.

3 likes
edoc's avatar
edoc
Best Answer
Level 24

@xingfucoder

use this

'something' => $faker->randomElement(['foo' ,'bar', 'baz']),
31 likes
ohffs's avatar

:: mutters about enum fields being evil :: ;-)

xingfucoder's avatar

Thanks @edoc for your reply, better than my method.

Hi @ohffs could you explain please about your enum field comment.

Thanks.

ohffs's avatar

Just that different databases do different things with them and it's easy to get trapped or encounter difficult to spot bugs. So in mysql prior to the new 5.7 (and depending on the config of 5.7) you can do :

create table enums (statuses enum('ok', 'error'));
insert into enums values('ok');
insert into enums values('hellokitty');
select * from enums;

| statuses |
+----------+
| ok       |
|          |

5.7 is a little different, another database is different to that, etc. I think it's just given programmers a feeling of safety where-as it's a bit more error-prone.

shayau's avatar

@egarcia In your Enum file add the following method:

public static function values(): array
{
    return array_column(self::cases(), 'value');
}

Then you can call it in in the factory like this:

 'something'  => $this->faker->randomElement(Something::values()),
3 likes
SevenZ's avatar

@shayau Easier:

'something'  => $this->faker->randomElement(Something::cases())->value
17 likes
da_Mask's avatar

For the googlers, You can pass the enum class directly into it, so if Something is a php enum, you can :

$randomEnum = fake()->randomElement( Something::class);

and get a random case.

5 likes

Please or to participate in this conversation.