PHPackages                             nathandunn/laravel-state-history - 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. [Database &amp; ORM](/categories/database)
4. /
5. nathandunn/laravel-state-history

ActiveLibrary[Database &amp; ORM](/categories/database)

nathandunn/laravel-state-history
================================

Laravel package for managing enum-based model states with enforced transitions and automatic status history tracking.

v1.0.6(2mo ago)01.7k↓90.5%[2 PRs](https://github.com/nthndnn/laravel-state-history/pulls)MITPHPPHP ^8.2CI passing

Since Aug 24Pushed 1w agoCompare

[ Source](https://github.com/nthndnn/laravel-state-history)[ Packagist](https://packagist.org/packages/nathandunn/laravel-state-history)[ RSS](/packages/nathandunn-laravel-state-history/feed)WikiDiscussions main Synced 3d ago

READMEChangelog (7)Dependencies (14)Versions (13)Used By (0)

🗃️ Laravel State History
========================

[](#️-laravel-state-history)

A Laravel package for managing **enum-based model states** with enforced transitions and automatic history tracking.

Features
--------

[](#features)

- **Native PHP Enums** (PHP 8.2+)
- **Enforced Transitions** with a pluggable state machine
- **Automatic History** with metadata
- **Smart Casting** of historical `from`/`to` values (enums, dates, primitives, custom casts)
- **Atomic Operations** – state change + history in one transaction
- **Current State Columns** (`current_{field}`) for indexing &amp; querying
- **Events, Guards &amp; Effects** for lifecycle hooks
- **Laravel 11–13 Support**

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

[](#installation)

```
composer require nathandunn/laravel-state-history
php artisan vendor:publish --provider="NathanDunn\StateHistory\StateHistoryServiceProvider" --tag="migrations"
php artisan migrate
```

Quick Start
-----------

[](#quick-start)

### 1. Define States

[](#1-define-states)

```
enum ArticleState: string
{
    case Draft = 'draft';
    case Published = 'published';
    case Archived = 'archived';
}
```

### 2. Create a State Machine

[](#2-create-a-state-machine)

```
use NathanDunn\StateHistory\Contracts\StateMachine;
use NathanDunn\StateHistory\TransitionMap;

class ArticleStateMachine implements StateMachine
{
    public function getTransitions(): TransitionMap
    {
        return TransitionMap::build(ArticleState::class)
            ->allowFromNull(ArticleState::Draft)
            ->allow(ArticleState::Draft, ArticleState::Published)
            ->allow(ArticleState::Published, ArticleState::Archived)
            ->allowAnyTo(ArticleState::Draft);
    }
}
```

### 3. Configure Your Model

[](#3-configure-your-model)

```
use NathanDunn\StateHistory\Traits\HasState;

class Article extends Model
{
    use HasState;

    protected $casts = [
        'state' => ArticleState::class,
    ];

    protected function stateMachine(): array
    {
        return ['state' => ArticleStateMachine::class];
    }
}
```

Usage
-----

[](#usage)

### Transitions

[](#transitions)

```
$article = Article::create(['state' => ArticleState::Draft]);

$article->transitionTo('state', ArticleState::Published, meta: [
    'editor' => 'alice'
]);
```

### Querying

[](#querying)

```
$published = Article::whereState('state', ArticleState::Published)->get();

if ($article->isInState('state', ArticleState::Published)) {
    // published
}

$allowed = $article->getAllowedTransitions('state');
```

### Current State

[](#current-state)

```
$state = $article->getState('state');     // ArticleState::Published
$raw   = $article->getCurrentState('state'); // "published"
```

### History

[](#history)

```
$history = $article->states('state');

foreach ($history as $h) {
    $from = $h->from; // Enum instance
    $to   = $h->to;
    $meta = $h->meta;
}
```

Advanced
--------

[](#advanced)

### Multiple State Fields

[](#multiple-state-fields)

```
class Order extends Model
{
    use HasState;

    protected $casts = [
        'status' => OrderStatus::class,
        'payment_status' => PaymentStatus::class,
    ];

    protected function stateMachine(): array
    {
        return [
            'status' => OrderStateMachine::class,
            'payment_status' => PaymentStateMachine::class,
        ];
    }
}
```

### Guards

[](#guards)

```
use NathanDunn\StateHistory\Contracts\Guard;

class PublishedArticleGuard implements Guard
{
    public function allows($model, $from, $to): bool
    {
        if ($to === ArticleState::Archived &&
            $model->published_at < now()->subDays(30)) {
            throw new \Exception('Must be published 30 days before archiving');
        }
        return true;
    }
}
```

### Effects

[](#effects)

```
use NathanDunn\StateHistory\Contracts\Effect;

class PublishEffect implements Effect
{
    public function execute($model, $from, $to): void
    {
        if ($to === ArticleState::Published) {
            $model->update(['published_at' => now()]);
        }
    }
}
```

### Events

[](#events)

- `StateTransitioning` – fired before a transition
- `StateTransitioned` – fired after success

```
use NathanDunn\StateHistory\Events\StateTransitioned;

Event::listen(StateTransitioned::class, function ($event) {
    Log::info("Model {$event->model->id} {$event->from} → {$event->to}");
});
```

Current State Columns
---------------------

[](#current-state-columns)

Optional `current_{field}` columns improve indexing &amp; analytics.

```
Schema::table('articles', function (Blueprint $t) {
    $t->string('current_state')->nullable()->index();
});
```

Config (`config/state-history.php`):

```
return [
    'use_current_columns' => true,
    'prefix' => 'current_',
    'model' => \App\Models\CustomStateHistory::class,
];
```

State Casting
-------------

[](#state-casting)

History values auto-cast to configured types:

```
foreach ($article->states('state') as $h) {
    $from = $h->from; // Enum
    $to   = $h->to;
}
```

Supports: **enums, dates, primitives, custom casts**.

###  Health Score

46

—

FairBetter than 92% of packages

Maintenance91

Actively maintained with recent releases

Popularity18

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 82.1% 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 ~38 days

Recently: every ~57 days

Total

7

Last Release

84d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/2cfa98e05be85f27d46b66803993a1b752a9c81dd448ca22f18f2a85ce050e1c?d=identicon)[nathandunn](/maintainers/nathandunn)

---

Top Contributors

[![nthndnn](https://avatars.githubusercontent.com/u/1976300?v=4)](https://github.com/nthndnn "nthndnn (32 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (7 commits)")

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/nathandunn-laravel-state-history/health.svg)

```
[![Health](https://phpackages.com/badges/nathandunn-laravel-state-history/health.svg)](https://phpackages.com/packages/nathandunn-laravel-state-history)
```

###  Alternatives

[api-platform/laravel

API Platform support for Laravel

58171.6k14](/packages/api-platform-laravel)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[yajra/laravel-oci8

Oracle DB driver for Laravel via OCI8

8793.2M25](/packages/yajra-laravel-oci8)[glushkovds/phpclickhouse-laravel

Adapter of the most popular library https://github.com/smi2/phpClickHouse to Laravel

2051.5M2](/packages/glushkovds-phpclickhouse-laravel)

PHPackages © 2026

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