https://github.com/ekvedaras/laravel-enum
🔠Laravel integration of ekvedaras/php-enum package
https://github.com/ekvedaras/laravel-enum
casting enum laravel laravel-enum php php-enum
Last synced: 12 months ago
JSON representation
🔠Laravel integration of ekvedaras/php-enum package
- Host: GitHub
- URL: https://github.com/ekvedaras/laravel-enum
- Owner: ekvedaras
- License: mit
- Created: 2020-08-30T14:40:05.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2021-09-20T09:07:01.000Z (over 4 years ago)
- Last Synced: 2025-01-11T08:14:43.851Z (about 1 year ago)
- Topics: casting, enum, laravel, laravel-enum, php, php-enum
- Language: PHP
- Homepage:
- Size: 16.6 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG-1.x.md
- License: LICENSE
Awesome Lists containing this project
README
# Laravel Enum

[](https://app.codecov.io/gh/ekvedaras/laravel-enum)
[](LICENSE)
[](https://packagist.org/packages/ekvedaras/laravel-enum)
[](https://packagist.org/packages/ekvedaras/laravel-enum)


This package integrates [ekvedaras/php-enum](https://github.com/ekvedaras/php-enum)
into Laravel by providing [enum value casting in models](https://laravel.com/docs/7.x/eloquent-mutators#custom-casts) which was introduced in Laravel 7.
## Usage
**PaymentStatus.php**
```php
use EKvedaras\LaravelEnum\Enum;
class PaymentStatus extends Enum
{
/**
* @return static
*/
final public static function pending(): self
{
return static::get('pending', 'Payment is pending');
}
/**
* @return static
*/
final public static function completed(): self
{
return static::get('completed', 'Payment has been processed');
}
/**
* @return static
*/
final public static function failed(): self
{
return static::get('failed', 'Payment has failed');
}
}
```
### Casting
**Payment.php**
```php
use Illuminate\Database\Eloquent\Model;
class Payment extends Model
{
protected $casts = [
'status' => PaymentStatus::class,
];
}
```
Setting and retrieving status:
```php
$payment = new Payment();
// It is advised to always set enum objects instead of strings for better usage analysis
$payment->status = PaymentStatus::pending();
// However, above works the same as this
$payment->status = 'pending';
// or this
$payment->status = PaymentStatus::pending()->id();
dump($payment->status === PaymentStatus::pending()); // true
$payment->status = 'invalid'; // throws OutOfBoundsException
```
### Validation
A built in `in` validator can be used.
```php
use Illuminate\Validation\Rule;
$rules = [
'status' => Rule::in(PaymentStatus::keys())
];
// or
$rules = [
'status' => 'in:' . PaymentStatus::keyString(),
];
```
## Changelog
See changes in changelog files:
* [v1 changelog](CHANGELOG-1.x.md)