Skip to content

Use myclabs/php-enum as Eloquent model attributes

Notifications You must be signed in to change notification settings

kminek/laravel-enum

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Laravel Enum

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

About

Use myclabs/php-enum as Eloquent model attributes

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages