PHPackages                             tamkeen-tech/laravel-enum-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. tamkeen-tech/laravel-enum-state-machine

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

tamkeen-tech/laravel-enum-state-machine
=======================================

Control your state using enums

v3.0.0(2mo ago)142.1k↑310.7%4MITPHPPHP ^8.0

Since Nov 1Pushed 2mo ago2 watchersCompare

[ Source](https://github.com/TamkeenTech/laravel-enum-state-machine)[ Packagist](https://packagist.org/packages/tamkeen-tech/laravel-enum-state-machine)[ RSS](/packages/tamkeen-tech-laravel-enum-state-machine/feed)WikiDiscussions main Synced yesterday

READMEChangelog (6)Dependencies (6)Versions (9)Used By (0)

[![Latest Version on Packagist](https://camo.githubusercontent.com/c43610ddebb1457f32dd6ce327a4d6b7701852e6a9f08c3611ccac4edaa297d6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f74616d6b65656e2d746563682f6c61726176656c2d656e756d2d73746174652d6d616368696e652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tamkeen-tech/laravel-enum-state-machine)[![Total Downloads](https://camo.githubusercontent.com/f31398e95296438bdb2ce200c9b445fd0831e3768771e5323bfefe724e60f180/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f74616d6b65656e2d746563682f6c61726176656c2d656e756d2d73746174652d6d616368696e652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tamkeen-tech/laravel-enum-state-machine)

Introduction
============

[](#introduction)

This package simplify controlling the transition between model states, allowing you to prevent unlogically transition and also controlling the initial state of the model using the PHP enums. Each enum allows you to define your states, the allowed transitions and the initial state, all in one place.

Laravel Enum State Machine, also allows you to automatically record the history of the state transition for each define state machine.

This package is built to help developers with the least amount of work needed to get it working.

Installation
============

[](#installation)

You can install the package via composer:

```
composer require tamkeen-tech/laravel-enum-state-machine
```

Next, if you going to record the history

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

To publish the config file, you can use the following command:

```
php artisan vendor:publish --tag=enum-state-machine-configs
```

Usage
=====

[](#usage)

Imagine you have bill with statuses, so at your bill model you will need to use `HasStateMachines` trait, and define your `protected $stateMachines` array variable to include all the fields that you going to apply the state machine on, and finally an optional variable `protected $recordStateHistory` boolean to either save history or not.

```
use TamkeenTech\LaravelEnumStateMachine\Traits\HasStateMachines;

class Bill extends Model
{
    use HasStateMachines;

    protected $fillable = [
        'status',
    ];

    protected $casts = [
        'status' => BillStatus::class,
    ];

    protected $recordStateHistory = true;

    protected $stateMachines = [
        'status'
    ];
}
```

In your `BillStatus` class you need to use trait `StateMachine` and to add two methods `transitions` to define your transition array and `initialState` to define the allowed initial states, both must return array.

```
use TamkeenTech\LaravelEnumStateMachine\Traits\StateMachine;

enum BillStatus: string
{
    use StateMachine;

    case PENDING = 'PENDING';
    case PAID = 'PAID';
    case EXPIRED = 'EXPIRED';
    case REFUNDED = 'REFUNDED';

    public function transitions(): array
    {
        return match ($this) {
            self::PENDING => [self::PAID, self::EXPIRED],
            self::PAID => [self::REFUNDED]
        };
    }

    public function initialState(): array
    {
        return [self::PENDING];
    }
}
```

From the example above the allowed transitions for `PENDING` case are `PAID` and `EXPIRED`, and the initail state for bill must be only `PENDING`

Now you are all done, you can start writing your code safely. So now if your tried to create a bill with different state you will receive an exception.

**Example**

- create bill with different initail state

    ```
    // throw InitailStateIsNotAllowedException with message "Only allowed initial states: PENDING"
    Bill::create([
      'status' => BillStatus::PAID
    ]);
    ```
- try to update to invalid transition

    ```
    $bill = Bill::create([
      'status' => BillStatus::PENDING
    ]);

    // throw StateTransitionNotAllowedException with message "Only allowed transition states: PAID, EXPIRED"
    $bill->update([
      'status' => BillStatus::REFUNDED
    ]);
    ```

State History Recording
=======================

[](#state-history-recording)

When you enable state history recording by setting protected `$recordStateHistory = true` in your model, the package will automatically track all state changes for the fields defined in `$stateMachines`.

Each state change will be recorded in the state\_machine\_histories table with the following information:

- The previous state (from)
- The new state (to)
- The field name that changed
- The model type and ID
- Timestamps of the change

You can access the state history through the stateHistory relationship:

```
$bill = Bill::find(1);
$bill->stateHistory;
```

Flow Diagram Generation
=======================

[](#flow-diagram-generation)

You can generate a flow diagram of your state machine using the following command:

```
php artisan enum:flow-diagram "App\Enums\BillStatus"
```

You can specify a custom output directory using the --output option

```
php artisan enum:flow-diagram "App\Enums\BillStatus" --output=/custom/path
```

This command will create a visual representation of your state machine as a PNG file, making it easier to understand the transitions between states.

Helper Methods
==============

[](#helper-methods)

The `StateMachine` trait provides several helper methods to make working with state transitions easier.

### `canTransitTo`

[](#cantransitto)

This method checks if the current state can transition to a given state.

**Example**

```
$billStatus = BillStatus::PENDING;

if ($billStatus->canTransitTo(BillStatus::PAID)) {
    // Do something
}
```

### `inInitialState`

[](#ininitialstate)

This method checks if the current state is one of the allowed initial states.

**Example**

```
$billStatus = BillStatus::PENDING;

if ($billStatus->inInitialState()) {
    // Do something
}
```

### `is`

[](#is)

This method checks if the current state is equal to a given state.

**Example**

```
$billStatus = BillStatus::PENDING;

if ($billStatus->is(BillStatus::PENDING)) {
    // Do something
}
```

### Changelog

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

### Security

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Andrés laravel-eloquent-state-machines](https://github.com/asantibanez/laravel-eloquent-state-machines)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

50

—

FairBetter than 95% of packages

Maintenance83

Actively maintained with recent releases

Popularity31

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 50% 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 ~179 days

Recently: every ~129 days

Total

8

Last Release

87d ago

Major Versions

v1.2.4 → v2.0.02025-02-27

v2.0.0 → v3.0.02026-04-07

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/13520828?v=4)[Shreif Elagami](/maintainers/shreifelagamy)[@shreifelagamy](https://github.com/shreifelagamy)

---

Top Contributors

[![shreifelagamy](https://avatars.githubusercontent.com/u/13520828?v=4)](https://github.com/shreifelagamy "shreifelagamy (6 commits)")[![abublihi](https://avatars.githubusercontent.com/u/10172039?v=4)](https://github.com/abublihi "abublihi (2 commits)")[![Abdulhakiem](https://avatars.githubusercontent.com/u/67789816?v=4)](https://github.com/Abdulhakiem "Abdulhakiem (1 commits)")[![Aldoggutierrez](https://avatars.githubusercontent.com/u/55823142?v=4)](https://github.com/Aldoggutierrez "Aldoggutierrez (1 commits)")[![devmoath](https://avatars.githubusercontent.com/u/28797003?v=4)](https://github.com/devmoath "devmoath (1 commits)")[![Moustafa-Alwakil](https://avatars.githubusercontent.com/u/84622028?v=4)](https://github.com/Moustafa-Alwakil "Moustafa-Alwakil (1 commits)")

---

Tags

laravelenumstatestate-machine

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/tamkeen-tech-laravel-enum-state-machine/health.svg)

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

###  Alternatives

[grumpydictator/firefly-iii

Firefly III: a personal finances manager.

23.9k69.5k](/packages/grumpydictator-firefly-iii)[firefly-iii/data-importer

Firefly III Data Import Tool.

8035.8k](/packages/firefly-iii-data-importer)[markwalet/nova-modal-response

A Laravel Nova asset for Modal responses on an action.

17878.9k](/packages/markwalet-nova-modal-response)[ronasit/laravel-helpers

Provided helpers function and some helper class.

2085.6k31](/packages/ronasit-laravel-helpers)[team-nifty-gmbh/tall-datatables

Server-side rendered datatables for Laravel and Livewire

1320.9k4](/packages/team-nifty-gmbh-tall-datatables)[iteks/laravel-enum

A comprehensive Laravel package providing enhanced enum functionalities, including attribute handling, select array conversions, and fluent facade interactions for robust enum management in Laravel applications.

2519.3k](/packages/iteks-laravel-enum)

PHPackages © 2026

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