Search by

datomatic / laravel-enum-state-machine

trippo

Guard the transitions of enum attributes on Laravel Eloquent models

Package info

github.com/datomatic/laravel-enum-state-machine

pkg:composer/datomatic/laravel-enum-state-machine

Fund package maintenance!

Datomatic

Statistics

Installs: 2 091

Dependents: 0

Suggesters: 0

Stars: 3

Open Issues: 0

v1.0.0 2026-11-21 11:13 UTC

This package is auto-updated.

Last update: 2026-11-21 11:16:54 UTC


README

Enum Helper-DarkEnum Helper-Light

Laravel enum state machine

Latest Version on Packagist Pest Tests number GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Guard the transitions of enum attributes on your Eloquent models.

Cast an attribute with AsEnumStateMachine, describe which transitions are allowed, and every assignment is checked: a denied transition throws StatusTransitionDenied (or is logged, in soft mode). It is a lightweight transition guard, not a full implementation of the state pattern.

Pure enums, int and string backed enums are supported.

Requirements

Package Version
PHP 8.2 – 8.6
Laravel 11, 12, 13

Installation

composer require datomatic/laravel-enum-state-machine

Optionally publish the config file:

php artisan vendor:publish --tag="enum-state-machine-config"
return [
    // Log denied transitions instead of throwing StatusTransitionDenied
    'soft_mode' => (bool) env('LARAVEL_ENUM_STATE_MACHINE_SOFT_MODE', false),

    // Log channel (null = default channel) and level used in soft mode
    'log_channel' => env('LARAVEL_ENUM_STATE_MACHINE_LOG_CHANNEL'),
    'log_level' => env('LARAVEL_ENUM_STATE_MACHINE_LOG_LEVEL', 'error'),
];

Usage

1. Cast the attribute

use Datomatic\LaravelEnumStateMachine\Casts\AsEnumStateMachine;
use Datomatic\LaravelEnumStateMachine\Concerns\HasEnumStateMachine;

class Order extends Model
{
    use HasEnumStateMachine; // optional, adds canTransitionTo()

    protected function casts(): array
    {
        return [
            'status' => AsEnumStateMachine::of(OrderStatus::class),
            'payment_status' => AsEnumStateMachine::of(PaymentStatus::class, softMode: true),
        ];
    }
}

The second argument of of() overrides the soft_mode config for that attribute: true enables it, false disables it, null (default) uses the config. The string syntax works as well: AsEnumStateMachine::class.':'.OrderStatus::class.',true'.

2. Define the allowed transitions

$from is null when the attribute has no value yet (the initial state), $to is null when the attribute is being cleared. Assigning the current value again is always allowed and is not checked.

On the enum, implementing HasTransitions. The rules live with the states and are shared by every model using the enum:

use Datomatic\LaravelEnumStateMachine\Contracts\HasTransitions;
use Illuminate\Database\Eloquent\Model;

enum OrderStatus: string implements HasTransitions
{
    case Pending = 'pending';
    case Paid = 'paid';
    case Shipped = 'shipped';
    case Cancelled = 'cancelled';

    public static function canTransition(?UnitEnum $from, ?UnitEnum $to, Model $model): bool
    {
        return match ($from) {
            null => $to === self::Pending,
            self::Pending => in_array($to, [self::Paid, self::Cancelled], true),
            self::Paid => $to === self::Shipped,
            default => false, // Shipped and Cancelled are final states
        };
    }
}

On the model, with a method named after the attribute (camelCase) followed by Transitions. It takes precedence over the enum rules, so you can use it to override them for a single model:

class Order extends Model
{
    public function statusTransitions(?OrderStatus $from, ?OrderStatus $to): bool
    {
        return match ($from) {
            null => true,
            OrderStatus::Pending => $to !== null,
            default => false,
        };
    }
}

When neither is defined, every transition is allowed.

3. Assign values

Enum cases, backing values and (for pure enums) case names are accepted:

$order = Order::create(['status' => OrderStatus::Pending]);

$order->status = OrderStatus::Paid; // OK
$order->status = 'shipped';         // OK
$order->status = OrderStatus::Pending; // throws StatusTransitionDenied

The exception exposes the transition:

use Datomatic\LaravelEnumStateMachine\Exceptions\StatusTransitionDenied;

try {
    $order->status = OrderStatus::Pending;
} catch (StatusTransitionDenied $exception) {
    $exception->model;     // the Order
    $exception->attribute; // 'status'
    $exception->from;      // OrderStatus::Shipped
    $exception->to;        // OrderStatus::Pending
}

Checking a transition without applying it

With the HasEnumStateMachine trait, for example to show or hide a button:

$order->canTransitionTo('status', OrderStatus::Shipped); // bool

Soft mode

In soft mode a denied transition does not throw: the value is applied and a message is written to the configured log channel and level, with the model class, key, attribute, from and to in the context.

Events

Event When
Datomatic\LaravelEnumStateMachine\Events\Transitioning an allowed transition is applied to the attribute (before the model is saved)
Datomatic\LaravelEnumStateMachine\Events\TransitionDenied a transition is denied, before the exception is thrown or the message is logged ($event->softMode tells which)

Both expose model, attribute, from and to.

Event::listen(function (TransitionDenied $event) {
    report("Denied {$event->attribute} transition on order {$event->model->getKey()}");
});

Using Laravel IDE Helper?

If you are using Laravel IDE Helper, publish the model hook:

php artisan vendor:publish --tag="enum-state-machine-ide-helper-hooks"

and add it to the model_hooks array in config/ide-helper.php:

'model_hooks' => [
    // ...
    \App\Support\IdeHelper\LaravelEnumStateMachineModelIdeHelperHook::class,
],

Upgrading from 0.x

  • Laravel 10 is no longer supported.
  • StatusTransitionDenied is now built with the model, the attribute and the from/to enums (all available as public properties) and its message changed. Update the code that creates or parses it.
  • The soft mode argument of the cast is parsed as a boolean: ',false' and of(Enum::class, false) now really disable soft mode (before, ',false' enabled it and of(..., false) fell back to the config).
  • Soft mode logs through log_channel/log_level (default: the default channel, error) with the details in the log context.
  • Assigning the current value again no longer marks the attribute as dirty.
  • A backed value of 0 (or '') is now treated as a state, not as the initial null state.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.