kminek/laravel-enum

Use myclabs/php-enum as Eloquent model attributes

v1.0.0 2021-09-15 16:14 UTC

This package is auto-updated.

Last update: 2024-11-15 23:25:30 UTC


README

Use most popular enum implementation for PHP
myclabs/php-enum as Eloquent model attributes.

Installation

composer require kminek/laravel-enum

Usage

Instead of using base enum class from myclabs/php-enum:

use \MyCLabs\Enum\Enum;

class Brand extends Enum
{
    public const TOYOTA = 'toyota';
    public const BMW = 'bmw';
    public const PEUGEOT = 'peugeot';
}

use enum class from this package:

use \Kminek\LaravelEnum\Enum;

class Brand extends Enum
{
    public const TOYOTA = 'toyota';
    public const BMW = 'bmw';
    public const PEUGEOT = 'peugeot';
}

Setup model attribute to use enum class:

class Car extends \Illuminate\Database\Eloquent\Model
{
    protected $casts = [
        'brand' => Brand::class,
    ];
}

If you would like to allow null values also:

class Car extends \Illuminate\Database\Eloquent\Model
{
    protected $casts = [
        'brand' => Brand::class.':nullable',
    ];
}

From now on you can get/set enums:

// set
$car = new Car();
$car->brand = new Brand(Brand::BMW);
// or
$car->brand = Brand::BMW;

// get
$brand = $car->brand; // $brand is enum instance

Running tests

composer test

Coding standards fixer

composer cs