bjerke/laravel-enums
| Install | |
|---|---|
composer require bjerke/laravel-enums |
|
| Latest Version: | v2.1.0 |
| PHP: | ^8.1 |
| License: | MIT |
| Last Updated: | Apr 29, 2023 |
| Links: | GitHub · Packagist |
Laravel Enums
This package provides a trait with helper methods for enum management and translation in Laravel.
Important: This package has been rebuilt as of v2 to work with native PHP enums instead of class constants. As such, PHP 8.1 is now required. See UPGRADE.md for more details.
Requirements:
- PHP 8.1 or higher
- Will only work with backed enums
Installation:
composer require bjerke/laravel-enums
Usage:
namespace App\Enums;
use Bjerke\Enum\HasTranslations;
use Bjerke\Enum\UsesTranslations;
enum PostStatus: int implements HasTranslations {
use UsesTranslations;
case DRAFT = 10;
case PUBLISHED = 20;
case ARCHIVED = 30;
}
Which will then allow you to define the translated versions of these values in Laravel translation file called enums.php:
// ../resources/lang/en/enum.php
use App\Enums\MyEnum;
return [
'post_status' => [
PostStatus::DRAFT->value => 'Draft',
PostStatus::PUBLISHED->value => 'Published'
PostStatus::ARCHIVED->value => 'Archived'
]
];
Which in turn will enable you to fetch the translated values as:
PostStatus::DRAFT->translate(); // return translation for this case
PostStatus::getTranslations(); // return all translations
There's also a helper method for retrieving cases:
PostStatus::getCasesAsArray() - Returns an array of "enum key" => "enum value"
Related Packages
A Laravel package for generating TypeScript/JavaScript enums and frontend transl...
Make your Laravel enums friendly with TypeScript, selects, and many more conveni...
Your framework-agnostic Swiss Army knife for PHP 8.1+ native enums
The integration-rich Laravel enum toolkit — attributes, state machines, bitmasks...
A state machine for Eloquent, built on native PHP enums. No state classes, no mo...