Automatically generate label from enum name

What happens when you need more than name and value?

Aaron Saray
Aaron Saray

I was so happy when I saw that Enums had finally come to PHP. Up until this time, I had been faking this sort of thing with constants on interfaces.

The times are changing, and I'm here for it.

In most Enum declarations, you'll find a simple set of key value pairs, or in the PHP language, a name and a value. The name allows you to reference it in your code. The value usually is stored or passed around as data.

So, what happens when you need to display something like a text label to the user?

My first thought was to create a method that used a PHP match statement and assign plain text values as return for a label() method.

Yuck! I heard you say that.

But what should we do then?

During one of my last projects, I came up with a PHP Trait that I think helps solve this problem.

As long as you name your name the same thing you'd want the user to see as a label.

You ready?

trait ProvidesLabelsById
    public function label(): string
        return __(ucwords(strtolower($this->name)));

Then, add this trait to every Enum that you want and you'll have a label now. You can use it something like this:

echo App\Enums\Permissions::UPDATE_USER_PROFILE->label();

The output will be Update User Profile - nice!

Here to help,


PS: If you figured out my secret message from the first letter of every sentence above the code samples, help me celebrate with a tip?

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.