Laravel Enum
Laravel Enum stats
- Downloads
- 2.3M
- Stars
- 291
- Open Issues
- 3
- Forks
- 32
Laravel Enum support
Laravel Support for Spatie Enum
The spatie/laravel-enum package provides robust support for enums within Laravel applications, leveraging the features of the spatie/enum package. It simplifies the integration of strongly typed enums in various aspects of a Laravel project such as model attribute casting, validation, and request data transformation.
Main Features
- Model Attribute Casting: Facilitates the use of enums as Eloquent model attributes, ensuring type safety and ease of use in data interactions.
- Validation Rules: Offers a custom validation rule
EnumRuleto ensure request data matches expected enum values. - Request Data Transformation: Allows automatic transformation of request data into enum instances, making controller logic cleaner and more robust.
- Route Binding: Supports automatic injection of enum instances into route actions, both implicitly and explicitly.
- Enum Make Command: Provides a convenient Artisan command to generate new enum classes.
- Faker Provider: Includes a provider to generate random enum values for use in factories, improving the ease of testing models with enum attributes.
Installation
Install the package via composer:
composer require spatie/laravel-enum
Usage
Define enums using the provided base class and utilize them in models, form requests, and routes. For example, to define an enum:
use Spatie\Enum\Laravel\Enum; final class StatusEnum extends Enum { // Define enum methods here}
Model attribute casting can be defined as:
protected $casts = [ 'status' => StatusEnum::class,];
For validation, use:
$rules = [ 'status' => new EnumRule(StatusEnum::class),];
And for transforming request data:
$request->transformEnums($enumCastRules);
Route binding and form requests are also supported, streamlining the handling of enums in route logic and validation processes.
Testing
Run package tests with:
composer test
Additional Resources
For detailed usage examples and advanced configuration options, refer to the package's GitHub repository. Here, you can also find information on contributing to the package, accessing the changelog, and handling security issues.