Laravel Statuses is a package that makes managing the model statuses easier. It provides a trait that you can use in your models to add statuses to them.
You can install the package via composer:
composer require uutkukorkmaz/laravel-statuses
You can publish the config file with:
php artisan vendor:publish --tag="statuses-config"
This is the contents of the published config file:
return [
'namespace' => 'Enums\\Statuses',
'allow_sequential' => true,
];
To create a new status, you can use the status:generate
command. This will generate an Enum
in your
project's app/Enums
directory.
php artisan status:generate OrderStatus
You can define cases for your status by adding constants to your Enum
class. The name of the constant will be used as
the case name, and the value will be used as the case value.
php artisan status:generate OrderStatus --cases Pending,Approved,Processing,Shipped,Delivered
The result of the above command will be:
<?php
namespace App\Enums\Statuses;
enum OrderStatus: string
{
case PENDING = 'pending';
case APPROVED = 'approved';
case PROCESSING = 'processing';
case SHIPPED = 'shipped';
case DELIVERED = 'delivered';
}
This type of statuses are used when the next status is always the next case in the enum. For example, if you have a
status for a user's account, the next status will always be the next case in the enum. For example, if the current
status is PENDING
, the next status will be APPROVED
.
php artisan status:generate AccountStatus --sequential --cases Pending,Approved
The result of the above command will be:
<?php
namespace App\Enums\Statuses;
enum AccountStatus: string
{
case PENDING = 'pending';
case APPROVED = 'approved';
public function next(): self
{
return match ($this) {
self::PENDING => self::APPROVED,
default => throw new \LogicException('Invalid status'),
};
}
public function previous(): self
{
return match($this) {
self::APPROVED => self::PENDING,
default => throw new \LogicException('Invalid status'),
};
}
}
To attach a status to a model, you can use the HasStatus
trait. This trait will add a status
field to your model.
use Uutkukorkmaz\LaravelStatuses\Concerns\HasStatus;
class Order extends Model
{
use HasStatus;
// ...
}
You can also attach status to a model automatically when creating the status with following command:
php artisan status:generate OrderStatus --model=Order --sequential --cases Pending,Approved,Processing,Shipped,Delivered
Please note that before the calling the command above you should have the model and the model must
have protected $casts
line.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
// ...
class Order extends Model
{
use HasStatus;
// ...
protected $casts = [
'status' => \App\Enums\Statuses\OrderStatus::class,
];
// ...
}
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
The MIT License (MIT). Please see License File for more information.