How to use the enumerations(Enums) of PHP 8.1 in Laravel?

Harish Kumar · · 7841 Views

The release of PHP 8.1 brings native enumerations to PHP. There is no more requirement for custom solutions in your Laravel projects since the Laravel v8.69 release has you back.

We'll take a straightforward example of a Post model. This Post model has the property status, and its possible values can be draft, in_review, or published. As it will be stored in the database, we will create a backed Enum. It implies that each enum case is associated with a string.

<?php

namespace App\Enums;

enum PostStatus: string
{
    case Draft = "draft";
    case InReview = "in_review";
    case Published = "published";
}

Now here comes the great part. In Laravel v8.69, it allows us for casting Enums. We can use the new casting in the Post model, and it allows a status attribute to be cast to/from an Enum:

<?php

namespace App\Models;

use App\Enums\PostStatus;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $casts = [
        'status' => PostStatus::class
    ];
}

It will cast the post status to Enum when interacting with the status attribute:

dd($post->status);

/*
App\Enums\PostStatus {
   name: "Published",
   value: "published",
 }
*/

The status attribute is cast to Enum, So you can access the backed value stored in the database if needed like so:

echo $post->status->value; // published

Or, in the Post model, you can add a method to compare status to the Enum directly:

public function isDraft()
{
    return $this->status === PostStatus::Draft;
}

public function isPublished()
{
    return $this->status === PostStatus::Published;
}

Create or Update Model

If you try to create or update a Post with an invalid status value, in that case, you will get PHP Fatal error:

$post->update(['status' => 'xyz']); 

/* Fatal Error: "xyz" is not a valid backing value for enum ... */

Validation rule

When you are updating or creating model status, its value is coming from the Form request. Then, it is important to validate the request to make sure an input contains a valid enum value.

Here is the example

Laravel v8.69 provides the Enum rule, a class-based rule that validates whether the field under validation contains a valid enum value:

use App\Enums\PostStatus;
use Illuminate\Validation\Rules\Enum;
 
$request->validate([
  'status' => [new Enum(PostStatus::class)],
]);

Now your request only accepts enum’s backed values.

0

Please login or create new account to add your comment.

0 comments
You may also like:

Exploring Asymmetric Property Visibility in PHP 8.4

The release of PHP 8.4 introduces a powerful new feature: Asymmetric Property Visibility, enabling developers to define separate visibility rules for reading and writing properties. (...)
Harish Kumar

What's New in PHP 8.4: Key Enhancements and Updates

As PHP 8.4's release on November 21, 2024, approaches, it's clear that PHP continues to evolve and delight its developer community. For those who have been coding with PHP since (...)
Harish Kumar

Introducing Tools to Supercharge PHP-FPM Efficiency and Monitoring

PHP-FPM stands for PHP FastCGI Process Manager. It’s an improved way to manage PHP processes that makes web applications faster and more efficient. Instead of running each PHP (...)
Harish Kumar

Building a Real-Time Chat App with Laravel Reverb and Nuxt 3

Building a real-time chat application is a great way to understand the power of WebSockets and real-time communication. In this tutorial, we will walk through creating a Real-Time (...)
Harish Kumar

How to Set Up Nuxt 3 Authentication with Laravel Sanctum (Step-by-Step Guide)

In modern web development, securing your application’s authentication process is a top priority. For developers building Single Page Applications (SPA) or Server-Side Rendered (...)
Harish Kumar

PHP 8.4 Property Hooks: The Ultimate Guide for Developers

PHP 8.4, coming in November 2024, introduces a new feature called property hooks. This feature makes it easier to work with class properties by allowing you to define custom behavior (...)
Harish Kumar