Laravel Idea for PhpStorm - Full-featured IDE for productive artisans!

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
Battle Ready Laravel

The ultimate guide to auditing, testing, fixing and improving your Laravel applications so you can build better apps faster and with more confidence.

Visit Battle Ready Laravel
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
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
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
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Join the Mastering Laravel community logo

Join the Mastering Laravel community

Connect with experienced developers in a friendly, noise-free environment. Get insights, share ideas, and find support for your coding challenges. Join us today and elevate your Laravel skills!

Join the Mastering Laravel community
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
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
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 →
Enhance Validation Testing Precision with Laravel's assertOnlyJsonValidationErrors image

Enhance Validation Testing Precision with Laravel's assertOnlyJsonValidationErrors

Read article
Generate HTTP Fixtures from Live API Calls in Laravel image

Generate HTTP Fixtures from Live API Calls in Laravel

Read article
Confidently Extract Single Array Items with Laravel's Arr::sole() Method image

Confidently Extract Single Array Items with Laravel's Arr::sole() Method

Read article
Safely Retry API calls in Laravel image

Safely Retry API calls in Laravel

Read article
Laravel's AsHtmlString Cast for Elegant HTML Attribute Management image

Laravel's AsHtmlString Cast for Elegant HTML Attribute Management

Read article
NativePHP for Mobile v1 — Launching May 2 image

NativePHP for Mobile v1 — Launching May 2

Read article