Blog Detail

05

Jan
Use Strongly typed Enums within your Laravel Models  cover image

arrow_back Use Strongly typed Enums within your Laravel Models

The laravel-enum package provides extended support for our spatie/enum package in Laravel.
This package offers strongly typed enums in PHP. We don’t use a simple “value” representation, so you’re always working with the enum object. This allows for proper autocompletion and refactoring in IDEs.

Installation

You can install the package via composer:

composer require spatie/laravel-enum

Usage

// a Laravel specific base class
use Spatie\Enum\Laravel\Enum;

/**
 * @method static self DRAFT()
 * @method static self PREVIEW()
 * @method static self PUBLISHED()
 * @method static self ARCHIVED()
 */
final class StatusEnum extends Enum {}

Model Attribute casting

This package provides two custom casts and the \Spatie\Enum\Laravel\Enum also implements the \Illuminate\Contracts\Database\Eloquent\Castable interface.

use Illuminate\Database\Eloquent\Model;

class TestModel extends Model
{
    protected $casts = [
        'status' => StatusEnum::class,
        'nullable_enum' => StatusEnum::class.':nullable',
        'array_of_enums' => StatusEnum::class.':collection',
        'nullable_array_of_enums' => StatusEnum::class.':collection,nullable',
    ];
}

By using the casts the casted attribute will always be an instance of the given enum.

$model = new TestModel();
$model->status = StatusEnum::DRAFT();
$model->status->equals(StatusEnum::DRAFT());

Validation Rule

This package provides a validation rule to validate your request data against a given enumerable.

use Spatie\Enum\Laravel\Rules\EnumRule;

$rules = [
    'status' => new EnumRule(StatusEnum::class),
];

This rule validates that the value of status is any possible representation of the StatusEnum. But you can also use the simple string validation rule definition:

$rules = [
    'status' => [
        'enum:'.StatusEnum::class,
    ],
];

Request Data Transformation

A common scenario is that you receive an enumerable value as part of your request data. To let you work with it as a real enum object you can transform request data to an enum in a similar way to the model attribute casting.

Request macro

There is a request macro available which is the base for the other possible ways to cast request data to an enumerable.

$request->transformEnums($enumCastRules);

This is an example of request enum castings. There are three predefined keys available as constants on Spatie\Enum\Laravel\Http\EnumRequest to cast enums only in specific request data sets. All other keys will be treated as independent enum casts and are applied to the combined request data set.

use Spatie\Enum\Laravel\Http\EnumRequest;

$enums = [
    // cast the status key independent of it's data set
    'status' => StatusEnum::class,
    // cast the status only in the request query params
    EnumRequest::REQUEST_QUERY => [
        'status' => StatusEnum::class,
    ],
    // cast the status only in the request post data
    EnumRequest::REQUEST_REQUEST => [
        'status' => StatusEnum::class,
    ],
    // cast the status only in the request route params
    EnumRequest::REQUEST_ROUTE => [
        'status' => StatusEnum::class,
    ],
];

You can call this macro yourself in every part of your code with access to a request instance. Most commonly you will do this in your controller action if you don’t want to use one of the other two ways.

Form Requests

Form requests are the easiest way to cast the data to an enum.

use Illuminate\Foundation\Http\FormRequest;
use Spatie\Enum\Laravel\Http\Requests\TransformsEnums;
use Spatie\Enum\Laravel\Rules\EnumRule;

class StatusFormRequest extends FormRequest
{
    use TransformsEnums;

    public function rules(): array
    {
        return [
            'status' => new EnumRule(StatusEnum::class),
        ];
    }

    public function enums(): array
    {
        return [
            'status' => StatusEnum::class,
        ];
    }
}

The request data transformation is done after validation via the FormRequest::passedValidation() method. If you define your own passedValidation() method you have to call the request macro transformEnums() yourself.

protected function passedValidation()
{
    $this->transformEnums($this->enums());

    // ...
}

Enum Make Command

We provide an artisan make command which allows you to quickly create new enumerables.

php artisan make:enum StatusEnum

You can use –method option to predefine some enum values - you can use them several times.

For more details related to this package, please visit Github.

Published at : 05-01-2022

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project