Skip to content

zbundy/laravel-enums

Repository files navigation

Adding php 8.1 enum support to Laravel migrations

Latest Version on Packagist Test Check & fix styling Total Downloads

This package adds enum support to migrations that has arrived with the release of PHP 8.1.

Installation

You can install the package via composer:

composer require zbundy/laravel-enums

Usage

Let's say that you have the following UserStatus enum:

<?php

namespace App\Enums;

enum UserStatus: string
{
    case ACTIVE = 'active';
    case SUSPENDED = 'suspended';
    case BANNED = 'banned';
}

Then in your user migration you can create a status column and pass that fully qualified enum:

<?php

use App\Enums\UserStatus;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class SetupDatabase extends Migration
{
    public function up()
    {
        Schema::create("users", function (Blueprint $table) {
            $table->id();

            $table->enum("status", UserStatus::class);

            $table->string("username");
            $table->string("password");

            $table->rememberToken();
            $table->timestamps();
        });
    }
}

You may also set a default value by creating a DEFAULT constant in your enum that is assigned one enum case:

<?php

namespace App\Enums;

enum UserStatus: int
{
    case ACTIVE = 1;
    case SUSPENDED = 2;
    case BANNED = 3;

    public const DEFAULT = self::ACTIVE;
}

This is equivalent to doing the following:

<?php

use Zbundy\LaravelEnums;
use App\Enums\UserStatus;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class SetupDatabase extends Migration
{
    public function up()
    {
        Schema::create("users", function (Blueprint $table) {
            $table->id();

            $table
                ->enum("status", UserStatus::class)
                ->default(UserStatus::ACTIVE);

            $table->string("username");
            $table->string("password");

            $table->rememberToken();
            $table->timestamps();
        });
    }
}

Testing

composer test

Changelog

Please see CHANGELOG for more information about recent changes.

Contributing

Please see CONTRIBUTING for details regarding contributions.

Security

If you discover any security related issues, please use the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

About

Add php 8.1 enum support to Laravel

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published