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

Harish Kumar · · 3309 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:

Learn PHP Development from beginning.

PHP stance Hypertext Preprocessor, it's server-side scripting laungage and easy to use. PHP  also well  known for its speed, simplicity, flexibility features that have made it (...)
Programmer Desk

Part #3: Rule objects based custom validation in Laravel

Laravel comes with multiple ways to add custom validation rules to validate form request inputs. I have already explained some of the ways in the following article links:
Harish Kumar

Part #2: How to use Laravel's Validator::extend method for custom validation

Validation is important in any application as it validates a form before performing actions on it. It allows the user to know their input is accurate and confident about the operation (...)
Harish Kumar

Part #1: Closure-based Custom Laravel Validation

While I was working with Laravel, validation using closure came to my mind, and I know it will be helpful to you. This tutorial assists you with all what is the difference between (...)
Harish Kumar

What is the difference between classes vs enums in PHP 8.1?

One of the common questions that I have been asked is what is the difference between classes and enums. Class(es) and enum(s) share many similarities but differ in some aspects. (...)
Harish Kumar

What is Enumerations(Enums) in PHP 8.1? Enums in PHP v8.1 Explained in detail with examples.

PHP 8.1 added many new features, and Enumerations (Enum) is our favourite new feature. Enumerations (or enums for short) allow us to define a new structure similar to a class however (...)
Harish Kumar