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

Pixelairport's avatar

Get enum by value

Hi. I already had this question in the past https://laracasts.com/discuss/channels/site-improvements/get-enum-by-int-reverse?page=1&replyId=773110 , where I asked how can I get the enum for a value. This was the code:

enum Status: int
{
    case INITIATED = 0;
    case SUCCESS = 1;
    case DECLINED = 2;
}

public function slug(): string
{
    return match($this) {
        self::INITIATED => 'ini',
        self::SUCCESS => 'suc',
        self::DECLINED => 'dec'
}

and this the soltuion: $status = Status::from(2);

QUESTION:

How can I get the enum by slug? I mean when I have ini for example. How can I get INITIATED enum? Is this possible?

0 likes
2 replies
Sergiu17's avatar
Sergiu17
Best Answer
Level 60

a static function ?!

public static function getBy($slug)
{
    return match ($slug) {
        'ini' => self::INITIATED,
        'suc' => self::SUCCESS,
        'dec' => self::DECLINED,
    };
}

but not sure why you are doing this

2 likes
Pixelairport's avatar

@Sergiu17 ok thx. seems that is the only way. I hoped there is a function which comes with enums. Why I want to do that is hard to explain... In short: We have a project and need to import data. From a system which stored everything in files, which have a lot of input fields instead of having enums, booleans, numbers, So I have to find ways for each field to import it and put it in the right place in a new structured laravel system.

1 like

Please or to participate in this conversation.