A Laravel package that provides an easy and efficient way to work with enums in PHP, enhancing code readability and maintainability.
- Enum Definition: Define enums using a straightforward syntax.
- Value Retrieval: Retrieve enum values seamlessly.
- Key Retrieval: Access enum keys with ease.
- Array Conversion: Convert enums to arrays for flexible usage.
- Validation Rules: Integrate enum validation rules within Laravel's validation system.
- Localization Support: Support for translating enum values using Laravel's localization features.
Install the package via Composer:
composer require omaradel-tech/enum
Create a new enum by extending the Enum
class:
use OmarAdel\Enum\Enum;
class UserRole extends Enum
{
const ADMIN = 'admin';
const EDITOR = 'editor';
const VIEWER = 'viewer';
public static $langPath = 'enum::user_roles';
}
Access the value of an enum:
$adminRole = UserRole::ADMIN; // 'admin'
Get the key associated with a specific value:
$key = UserRole::ADMIN()->getKey(); // 'ADMIN'
Convert the enum to an associative array:
$array = UserRole::toArray();
/*
[
'ADMIN' => 'admin',
'EDITOR' => 'editor',
'VIEWER' => 'viewer',
]
*/
Use the enum in Laravel's validation rules:
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
public function store(Request $request)
{
$request->validate([
'role' => ['required', Rule::in(UserRole::values())],
]);
// ...
}
To localize enum values, add translations in your /lang/vendor/enum
files:
resources/lang/vendor/enum/en/user_roles.php:
return [
'admin' => 'Administrator',
'editor' => 'Editor',
'viewer' => 'Viewer',
];
Then, retrieve the localized value:
$translated = UserRole::getLabel(UserRole::ADMIN); // 'Administrator'
php artisan vendor:publish --tag=enum-translations
1- BaseUserEnum Class:
use OmarAdel\Enum\Enum;
class BaseUserEnum extends Enum
{
const ADMIN = 'Admin';
const USER = 'User';
}
2- BaseStatusEnum Class:
use OmarAdel\Enum\Enum;
class BaseStatusEnum extends Enum
{
const DRAFT = 'Draft';
const PENDING = 'Pending';
const PUBLISH = 'Published';
}
3- BaseUserStatusEnum Class:
use OmarAdel\Enum\Enum;
class BaseUserStatusEnum extends Enum
{
const ACTIVE = 'Active';
const IN_ACTIVE = 'In-Active';
}
Contributions are welcome! Please submit a pull request or open an issue to discuss improvements or features.
This package is open-sourced software licensed under the MIT license.