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.

image
Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Visit Paragraph
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

Bespoke software solutions built for your business. We ♥ Laravel

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
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with Vue and Livewire stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a 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

The latest

View all →
Configuring Laravel With Additional Environment Files image

Configuring Laravel With Additional Environment Files

Read article
Real Time Command Line Monitoring With Laravel Top image

Real Time Command Line Monitoring With Laravel Top

Read article
A New Validation Rule and the Ability to Manually Fail a Command in Laravel 11.8 image

A New Validation Rule and the Ability to Manually Fail a Command in Laravel 11.8

Read article
New Proposed Array Find Functions in PHP 8.4 image

New Proposed Array Find Functions in PHP 8.4

Read article
Laracon AU 2024 tickets are now on sale image

Laracon AU 2024 tickets are now on sale

Read article
Dash UI is a Laravel Blade Component Library Inspired by Shopify Polaris image

Dash UI is a Laravel Blade Component Library Inspired by Shopify Polaris

Read article