Extending PHP 8.1 enums with attributes

Published on by

Extending PHP 8.1 enums with attributes image

With the release of PHP 8.1, the language gained native support for enums. Enums are a type-safe, readable and efficient way to encapsulate a small set of possible values a field can take in your data model. Using classes instead of database enums provides more flexibility if you need to add to the list in the future.

As an example, you have a user data model and that user might have a specific list of roles you can choose from.

namespace App\Enums;
 
enum UserRole: string
{
case Admin = 'admin';
case TeamAdmin = 'team_admin';
case Support = 'support';
case Basic = 'basic';
}

In your data model, Laravel also has support for enums by casting them to the value if you define it in your casts array.

/**
* The attributes that should be cast.
*
* @var array<string,string|class-string>
*/
protected $casts = [
'role' => UserRole::class,
];

Adding the enum casting will ensure that an exception will be thrown if we try to save a role to our user model not defined in the enum.

A very practical use of enums is to generate values for a dropdown in your HTML

<select name=”roles”>
@foreach(UserRole::cases() as $role)
<option value="{{ $role->value }}">{{ $role->name }}</option>
@endforeach
</select>

On the surface, nothing seems wrong with the example above until you look at the visible name of each option in the dropdown. Admin and TeamAdmin are great variable names, but Administrator and Team Administrator would be better to present in the UI, so it is crystal clear what the role is to the person managing user roles.

While enums are great for simple name/value pairs, in cases like this where you need to add a 3rd property, you have to get creative.

Enter PHP attributes. Borrowed from the concept of annotations in other languages, it is a way to associate metadata to properties, methods and classes, which sounds exactly like what we need.

First, we need to build a Description attribute.

namespace App\Enums\Attributes;
 
use Attribute;
 
#[Attribute]
class Description
{
public function __construct(
public string $description,
) {
}
}

We now have a Description attribute we can leverage in our enum so we can define the user-friendly role names we desire.

namespace App\Enums;
 
enum UserRole: string
{
#[Description('Administrator')]
case Admin = 'admin';
 
#[Description('Team Administrator')]
case TeamAdmin = 'team_admin';
 
case Support = 'support';
case basic = 'basic';
}

Now we need to retrieve these attributes, which can only be done via reflection. Since we may want to reuse this attribute on other enums, we will want to make a trait to make this easier.

namespace App\Enums\Concerns;
 
use Illuminate\Support\Str;
use ReflectionClassConstant;
use App\Enums\Attributes\Description;
 
trait GetsAttributes
{
/**
* @param self $enum
*/
private static function getDescription(self $enum): string
{
$ref = new ReflectionClassConstant(self::class, $enum->name);
$classAttributes = $ref->getAttributes(Description::class);
 
if (count($classAttributes) === 0) {
return Str::headline($enum->value);
}
 
return $classAttributes[0]->newInstance()->description;
}
}

If we break this method down, the first 2 lines are using reflection to get the attributes of the enum. Since not every enum may have a Description attribute, we set up a fallback to transform the value (or name) of that enum as our description.

Lastly, we pull the value of the description from the enum attributes. We can add another method to our trait to handle this.

/**
* @return array<string,string>
*/
public static function asSelectArray(): array
{
/** @var array<string,string> $values */
$values = collect(self::cases())
->map(function ($enum) {
return [
'name' => self::getDescription($enum),
'value' => $enum->value,
];
})->toArray();
 
return $values;
}

Now, in our HTML, we can simply change the method we call on the enum class

<select name=”roles”>
@foreach(UserRoles::asSelectArray() as $role)
<option value={{ $role->value }}>{{ $role->name }}</option>
@endforeach
</select>

While they are relative newcomers to PHP, enums and attributes are great additions to the language and provide native support for many common use cases.

Rob Fonseca photo

Team Lead at Kirschbaum. Full-stack developer specializing in Laravel, Vue and Tailwind CSS.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
The Inertia.js v2 Beta is Here image

The Inertia.js v2 Beta is Here

Read article
Mastering Laravel, No Compromises, and SourceDive with Joel Clermont image

Mastering Laravel, No Compromises, and SourceDive with Joel Clermont

Read article
Now you can install PHP and the Laravel installer with a single command image

Now you can install PHP and the Laravel installer with a single command

Read article
WireSpy is a Sleek New Debug Bar for Laravel Livewire image

WireSpy is a Sleek New Debug Bar for Laravel Livewire

Read article
The Laracon AU schedule is now live image

The Laracon AU schedule is now live

Read article
Supercharge PhpStorm with Laravel Idea image

Supercharge PhpStorm with Laravel Idea

Read article