PHPackages                             caner/state-machine - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. caner/state-machine

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

caner/state-machine
===================

Transaction-safe state machines for Laravel Eloquent models

1.1.0(4y ago)51202MITPHPPHP ^8.0CI passing

Since Jan 12Pushed 2w ago5 watchersCompare

[ Source](https://github.com/CanerErgez/laravel-state-machine)[ Packagist](https://packagist.org/packages/caner/state-machine)[ Docs](https://github.com/CanerErgez/state-machine)[ RSS](/packages/caner-state-machine/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (3)Dependencies (3)Versions (13)Used By (0)

Laravel State Machine
=====================

[](#laravel-state-machine)

[![Latest Version on Packagist](https://camo.githubusercontent.com/89b1b9deb5846cab74ba3e16048881604d7e9c937c81b44c91b49a151a4248f3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f63616e65722f73746174652d6d616368696e652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/caner/state-machine)[![Total Downloads](https://camo.githubusercontent.com/61b2bd76510e309a8db75ef6e87edc64fa1b41432c0164bf5bc30e7a79c62280/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f63616e65722f73746174652d6d616368696e652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/caner/state-machine)[![run-tests](https://github.com/CanerErgez/laravel-state-machine/actions/workflows/main.yml/badge.svg?branch=main)](https://github.com/CanerErgez/laravel-state-machine/actions/workflows/main.yml)

Transaction-safe, guard-driven state machines for Laravel Eloquent models.

The package is designed for business workflows such as orders, payments, subscriptions, approvals, and fulfilment. A model may use multiple independent state machines.

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 12 or 13

Installation
------------

[](#installation)

```
composer require caner/state-machine
php artisan vendor:publish --tag=caner-state-machine-config
```

Laravel package discovery registers the provider automatically.

Five-minute example
-------------------

[](#five-minute-example)

Generate the building blocks:

```
php artisan make:state-machine Order/OrderStateMachine
php artisan make:state Order/States/Pending --machine="App\\StateMachines\\Order\\OrderStateMachine"
php artisan make:state Order/States/Paid --machine="App\\StateMachines\\Order\\OrderStateMachine"
php artisan make:transition Order/Transitions/MarkAsPaid
php artisan make:guard Order/Guards/PaymentCaptured
php artisan make:after-action Order/AfterActions/SendReceipt
```

Define the machine:

```
final class OrderStateMachine extends BaseStateMachine
{
    public function initialState(): int|string|BackedEnum
    {
        return OrderStatus::Pending;
    }

    public function states(): array
    {
        return [
            OrderStatus::Pending->value => Pending::class,
            OrderStatus::Paid->value => Paid::class,
        ];
    }

    public function transitions(): array
    {
        return [
            Pending::class => [
                Paid::class => MarkAsPaid::class,
            ],
        ];
    }
}
```

Use `HasState` on the model and run a transition:

```
$order = $order
    ->state(OrderStateMachine::class, 'status')
    ->transitionTo(
        Paid::class,
        new TransitionContext(
            data: $request->validated(),
            actor: $request->user(),
            metadata: ['source' => 'checkout'],
        ),
    );
```

Execution guarantees
--------------------

[](#execution-guarantees)

Each transition runs on the model's own database connection:

```
row lock → guards → action → state update → after actions → audit → commit

```

- A rejected guard stops the transition.
- An exception in the action or a synchronous after action rolls everything back.
- The row lock prevents two workers from applying transitions from the same stale state.
- Work that must happen only after commit should be dispatched from an after action with `Job::dispatch(...)->afterCommit()`.
- Unexpected exceptions are wrapped in `TransitionFailedException` and retained as `getPrevious()`. Guard and concurrency exceptions remain directly catchable.

Transition names and metadata
-----------------------------

[](#transition-names-and-metadata)

Transitions get a snake-case name automatically. Override it or provide static metadata when exposing actions to an API:

```
public function name(): string
{
    return 'capture_payment';
}

public function metadata(): array
{
    return ['label' => 'Capture payment', 'destructive' => false];
}
```

```
$machine->canTransitionTo(Paid::class);
$machine->allowedTransitions();
$machine->allowedTransitionDetails();
```

The query methods inspect the transition graph and never execute guards.

Audit history
-------------

[](#audit-history)

Publish and run the package migration:

```
php artisan vendor:publish --tag=caner-state-machine-migrations
php artisan migrate
```

Then enable history in `config/state-machine.php`. Audit rows are written inside the same transaction and contain the model, attribute, states, transition, actor, and merged transition/context metadata.

```
'history' => ['enabled' => true],
```

```
$order->stateTransitionHistory()->latest()->get();
```

You can replace the recorder by binding your own implementation of `TransitionHistoryRecorder`.

Mermaid diagrams
----------------

[](#mermaid-diagrams)

```
php artisan state-machine:diagram \
  "App\\StateMachines\\Order\\OrderStateMachine" \
  "App\\Models\\Order" 42 status \
  --output=docs/order-workflow.mmd
```

Multiple workflows
------------------

[](#multiple-workflows)

Use a different machine and attribute for each workflow:

```
$order->state(OrderStateMachine::class, 'status');
$order->state(PaymentStateMachine::class, 'payment_status');
```

Documentation
-------------

[](#documentation)

- [State machine](docs/first_state_machine.md)
- [States](docs/first_state.md)
- [Transitions](docs/first_transition.md)
- [Guards](docs/first_guard.md)
- [After actions](docs/first_after_action.md)
- [Running transitions](docs/example_transition.md)
- [Multiple state machines](docs/create_another_state_machine.md)
- [Upgrade from v1](docs/upgrade_v2.md)
- [Release checklist](docs/releasing.md)

Development
-----------

[](#development)

```
composer quality
```

This runs Pint, Larastan, and the PHPUnit suite. CI tests every supported Laravel/PHP combination.

Security
--------

[](#security)

Please follow the [security policy](SECURITY.md).

License
-------

[](#license)

The MIT License. See [LICENSE.md](LICENSE.md).

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance63

Regular maintenance activity

Popularity18

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~19 days

Total

3

Last Release

1640d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/21d3476626be33ce8a33692f025e5a2c797c97bfc1ec08cdba37eb3dd6b8d2ad?d=identicon)[CanerErgez](/maintainers/CanerErgez)

---

Top Contributors

[![CanerErgez](https://avatars.githubusercontent.com/u/10279602?v=4)](https://github.com/CanerErgez "CanerErgez (48 commits)")

---

Tags

laravelstate-machinecaner

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/caner-state-machine/health.svg)

```
[![Health](https://phpackages.com/badges/caner-state-machine/health.svg)](https://phpackages.com/packages/caner-state-machine)
```

###  Alternatives

[renatomarinho/laravel-page-speed

Laravel Page Speed

2.5k1.7M11](/packages/renatomarinho-laravel-page-speed)[emargareten/inertia-modal

Inertia Modal is a Laravel package that lets you implement backend-driven modal dialogs for Inertia apps.

90157.6k](/packages/emargareten-inertia-modal)[forjedio/inertia-table

Backend-driven dynamic tables for Laravel + Inertia.js

272.0k](/packages/forjedio-inertia-table)[tomshaw/electricgrid

A feature-rich Livewire package designed for projects that require dynamic, interactive data tables.

119.8k](/packages/tomshaw-electricgrid)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
