THIS PACKAGE IS STILL IN DEVELOPMENT, DO NOT USE YET
The package is based on the implementation of Enum from myclabs/php-enum.
ExampleModel
use App\Enums\ExampleStatusEnum;
use Illuminate\Database\Eloquent\Model;
use LeMaX10\Enums\Traits\ModelEnums;
/**
* Class ExampleModel
* @package App
*/
class ExampleModel extends Model
{
use ModelEnums;
/**
* @var array
*/
protected $enums = [
'status' => ExampleStatusEnum::class
];
}
ExampleStatusEnum
use LeMaX10\Enums\Enum;
/**
* Class ExampleStatusEnum
* @package App\Enums
*/
final class ExampleStatusEnum extends Enum
{
/**
*
*/
private const FOO = 'foo';
/**
*
*/
private const BAR = 'bar';
}
ExampleTranslatableEnum
use LeMaX10\Enums\Enum;
use LeMaX10\Enums\Contracts\Translatable;
/**
* Class ExampleStatusEnum
* @package App\Enums
*/
final class ExampleStatusEnum extends Enum implements Translatable
{
/**
*
*/
private const FOO = 'foo';
/**
*
*/
private const BAR = 'bar';
/**
* Translatable value
* @return string
*/
public function getTransValue(): string
{
return trans('enum.'. $this->value);
}
}
Request Validation Rules
<?php
namespace App\Http\Requests;
use App\Enums\ExampleStatusEnum;
use Illuminate\Http\Request;
class ExampleRequest extends Request
{
public function rules(): array
{
return [
'status' => 'required|enum:'. ExampleStatusEnum::class
];
}
}
or
<?php
namespace App\Http\Requests;
use App\Enums\ExampleStatusEnum;
use LeMaX10\Enums\Rules\EnumValue;
use Illuminate\Http\Request;
class ExampleRequest extends Request
{
public function rules(): array
{
return [
'status' => ['required', new EnumValue(ExampleStatusEnum::class)]
];
}
}
or
<?php
namespace App\Http\Requests;
use App\Enums\ExampleStatusEnum;
use Illuminate\Http\Request;
class ExampleRequest extends Request
{
public function rules(): array
{
return [
'status' => ['required', ExampleStatusEnum::rule()]
];
}
}
You can install the package via composer:
composer require LeMaX10/laravel-enums
Register the service provider in config/app.php from Laravel < 5.5:
'providers' => [
...
\LeMaX10\Enums\EnumServiceProvider::class,
...
]
You can synchronize the enums created in the database using the sync command.
- Create enum column or change exists column in table and run
Schema::create('tableName', function (Blueprint $table): void {
$table->increments('id');
$table->enum('status', array_values(ExampleStatusEnum::toArray()));
});
- Run sync command php artisan db:enum:sync App\Models\ExampleModel
$exampleModel = new ExampleModel;
$exampleModel->status = ExampleStatusEnum::FOO();
$exampleModel->save();
....
echo $exampleModel->status
See documentation myclabs/php-enum.
You can run the tests with:
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.