In this article, we will discuss the “Implementation Laravel Enum Package”. It is a wonderful resource for Laravel. As you know, Laravel provides lots of inbuilt features. Developers can create an open source package to return something to the Laravel community. It’s created by Ben Sampson that adding support for creating enums in PHP. It also includes a generator for Laravel.
Table of Contents
Prerequisites
Laravel fresh setup where we create a test case for this package. If you are not familiar with the Laravel then you can start with the given articles.
- Understanding Laravel Middleware
- Custom User Email Verification / Activation Laravel
- Laravel Default Authentication
- Email Verification Laravel 5.7
Laravel Enum Package Features
- Enum key-value pairs as class constants
- A full-featured suite of methods
- Enum artisan generator
- Validation rules for passing enum key or values as input parameters
- Localization support
- Extendible
Installation
You can use the following composer command to install the package.
composer require bensampo/laravel-enum
Generating Enum Class
Package having the builtin artisan command to generate Enum class.
php artisan make:enum UserType
Laravel Enum Package example of what an Enum class looks like:
<?php namespace App\Enums; use BenSampo\Enum\Enum; final class UserType extends Enum { const SuperAdministrator = 0; const Administrator = 1; const Editor = 2; const Author = 3; const Subscriber = 4; }
Here’s the list of available methods and examples of how to use this package.
Enum Controller Validations
Laravel Enum package provides two way to apply the validations “EnumValue” and “EnumKey”.
<?php ... public function store(Request $request) { // EnumValue Validations $this->validate($request, [ 'user_type' => ['required', new EnumValue(UserType::class)], ]); // EnumKey Validations $this->validate($request, [ 'user_type' => ['required', new EnumKey(UserType::class)], ]); } ...
Access Enum Value
You can use the following code snippet to get specific Enum value.
UserType::Editor // Returns 2
Conclusion
In this article, we will discuss the Laravel Enum Package. It’s a wonderful resource, you can check the official repository on GitHub. Hope you like this article. Please feel to add the comment if any query or submit your feedback 🙂
You may like:
Dump Server Laravel 5.7 New Feature
If you like our content, please consider buying us a coffee.
Thank you for your support!
Buy Me a Coffee