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.
Payment, Order, UserAccount). This aligns well with domain-driven design (DDD) and business workflows requiring strict state validation.state as string). Backward-compatible if the column is optional initially.laravel-activitylog for auditing state changes).Paid::class vs. paid) require directory organization to avoid resolution errors. Misconfiguration can lead to runtime exceptions.Paid → Pending without reversal logic).spatie/laravel-state-machine).laravel-activitylog or implement custom observers.$model->fresh()->state->transitionTo(...)) for race conditions.state column in all target tables, with default values set.amount > 0)? Extend state classes or use model observers.Order, Payment, Subscription).is_active booleans, status enums) for consolidation.Payment) to validate the approach.state column via migration:
Schema::table('payments', function (Blueprint $table) {
$table->string('state')->nullable()->after('amount');
});
PaymentState and concrete states (Pending, Paid, Failed).if ($order->status === 'shipped')) with state transitions.state column from legacy fields (e.g., status = 'active' → state = Active::class).getStates() results if listing states frequently (e.g., in admin panels).Payment::find(1)->state->transitionTo(Paid::class)->onQueue('state-transitions')).state columns in a single migration batch.HasStates trait and state classes to models in priority order (e.g., critical paths first).Spatie\ModelStates\Events\StateChanged) to catch issues early.allowTransition(), preventing invalid states at runtime.Paid to Pending not allowed").getStates() to inspect valid states for a model. Log state changes for auditing.StateConfig instances).state columns if querying by state frequently.| Failure Scenario | Mitigation | Detection |
|---|---|---|
| Invalid state transition | Use try-catch blocks or middleware to log/retry failed transitions. |
Exceptions in logs. |
| State resolution errors | Ensure state classes are in the correct directory. Use php artisan checks. |
ClassNotFoundException in logs. |
| Race conditions (concurrent updates) | Implement optimistic locking ($model->fresh() before transitions). |
Inconsistent state in logs/audits. |
| Database corruption (state column) | Add database constraints (e.g., check for valid state values). |
Failed queries or app crashes. |
| Missing state classes | Use registerStatesFromDirectory to auto-discover states. |
Runtime errors during state resolution. |
How can I help you explore Laravel packages today?