Package Data | |
---|---|
Maintainer Username: | nasyrov |
Maintainer Contact: | inasyrov@ya.ru (Evgenii Nasyrov) |
Package Create Date: | 2017-06-11 |
Package Last Update: | 2020-12-29 |
Home Page: | |
Language: | PHP |
License: | MIT |
Last Refreshed: | 2024-11-19 03:13:05 |
Package Statistics | |
---|---|
Total Downloads: | 66,640 |
Monthly Downloads: | 304 |
Daily Downloads: | 11 |
Total Stars: | 33 |
Total Watchers: | 2 |
Total Forks: | 9 |
Total Open Issues: | 0 |
Laravel package for Enum implementation.
Make sure all dependencies have been installed before moving on:
Pull the package via Composer:
$ composer require nasyrov/laravel-enums
Register the service provider in config/app.php
:
'providers' => [
...
Nasyrov\Laravel\Enums\EnumServiceProvider::class,
...
]
Generate a new enum class via the command:
$ php artisan make:enum UserStatusEnum
Define the enum constants:
/**
* @method static UserStatusEnum ACTIVE()
* @method static UserStatusEnum INACTIVE()
*/
class UserStatusEnum extends Enum
{
const ACTIVE = 10;
const INACTIVE = 20;
}
To use the enum new up the instance or simply call via the static methods:
$status = new UserStatusEnum(UserStatusEnum::ACTIVE);
$status = UserStatusEnum::ACTIVE();
Type-hint the model accessor:
public function getStatusAttribute($attribute) {
return new UserStatusEnum($attribute);
}
Type-hint the model mutator:
public function setStatusAttribute(UserStatusEnum $attribute) {
$this->attributes['status'] = $attribute->getValue();
}
Validation:
$this->validate($request, [
'status' => [
'required',
Rule::in(UserStatusEnum::values()),
],
]);
Localization:
use Nasyrov\Laravel\Enums\Enum as BaseEnum;
abstract class Enum extends BaseEnum
{
/**
* Get the enum labels.
*
* @return array
*/
public static function labels()
{
return static::constants()
->flip()
->map(function ($key) {
// Place your translation strings in `resources/lang/en/enum.php`
return trans(sprintf('enum.%s', strtolower($key)));
})
->all();
}
}
<select name="status">
@foreach (UserStatusEnum::labels() as $value => $label)
<option value="{{ $value }}">
{{ $label }}
</option>
@endforeach
</select>
$ composer lint
$ composer test
If you discover any security related issues, please email inasyrov@ya.ru instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.