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. nathandunn/laravel-state-history

ActiveLibrary

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

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

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

Since Aug 24Pushed 3mo 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 1mo ago

READMEChangelog (6)Dependencies (7)Versions (10)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–12 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

44

—

FairBetter than 92% of packages

Maintenance82

Actively maintained with recent releases

Popularity20

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 81.8% 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 ~33 days

Recently: every ~42 days

Total

6

Last Release

99d 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 (27 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (6 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

[fumeapp/modeltyper

Generate TypeScript interfaces from Laravel Models

196277.9k](/packages/fumeapp-modeltyper)[api-platform/laravel

API Platform support for Laravel

59126.4k6](/packages/api-platform-laravel)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

44643.1k1](/packages/pressbooks-pressbooks)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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