spatie/laravel-model-states
Add state and state machine behavior to Eloquent models. Represent each state as its own class, automatically cast and store states in the database, and define clean, safe transitions and state-specific behavior in your Laravel apps.
Pending → Paid but not Paid → Pending) without custom middleware or monolithic logic, reducing bugs and improving auditability.Order, Subscription) with clear state transitions.color() example).if-else checks (e.g., "Is this order shipped?") with declarative state transitions.Cancelled order cannot be Shipped") at the model level.StateChanged events) for reporting or debugging.Adopt When:
Draft → Published → Archived).spatie/laravel-state-machine).Look Elsewhere When:
active/inactive flags) and don’t require transitions or complex logic."This package lets us model complex business workflows (like orders or subscriptions) as self-documenting state machines, reducing errors and making rules easier to audit. For example, we can enforce that an order can’t be ‘shipped’ if it’s ‘cancelled’—without writing spaghetti code. It also unlocks features like dynamic UI updates (e.g., showing ‘green’ for ‘Paid’ orders) and better analytics by tracking state changes. The trade-off is minimal: a small upfront investment to standardize workflows across the codebase, with long-term gains in maintainability and scalability."
Key Outcomes:
*"This is a batteries-included solution for state management in Laravel, combining the State Pattern (encapsulate state-specific behavior) with State Machine rules (define allowed transitions). It’s ideal for:
Order states (Draft → Pending → Shipped → Delivered) with validation.Why not build it ourselves?
Proposal:
Subscription).State base class and naming conventions.StateChanged events).STATE_MANAGEMENT.md guide for the team."*Alternatives Considered:
spatie/laravel-state-machine is more rigid; this offers more flexibility (e.g., PHP 8 attributes, custom events).How can I help you explore Laravel packages today?