hxm/enum

Enum package, simple, extensible and powerful enumeration implementation for Laravel.

1.0.4 2022-04-26 04:27 UTC

This package is auto-updated.

Last update: 2024-10-27 05:52:15 UTC


README

Simple installation, extensible and powerful enumeration implementation for Laravel.

  • Enum key value pairs as class constants
  • Attribute casting
  • Validation rules for passing enum values as input parameters

Installation

Via Composer

composer require hxm/enum

Basic Usage

Now, you just need to add the possible values your enum can have as constants.

<?php
namespace App\Enums;

use HXM\Enum\Abstracts\EnumBase;

class ExampleEnums extends EnumBase
{
    const E1 = 1;
    const E2 = 2;

    protected static $descriptions = [
        1 => 'description for E1'
    ];
}
  ExampleEnums::E1; // 1
  
  ExampleEnums::getValueWithDescriptions()->toArray(); // [1 => 'description for E1', 2 => "E2"]
  
  ExampleEnums::getValues()->toArray(); // [1, 2]
  
  ExampleEnums::getDescription(1); // 'description for E1'
  

Get Casting

use in Model Class

class ExampleClass extends Model
{
  protected $casts = [
          ....
          'attribute' => ExampleEnums::class,
          ...
      ];
}

Get Rule

Validator:make($data, [
  'attribute' => ['required', ExampleEnums::getRule()]
]);