App-owned state transitions in Laravel PHP
Scope
Inline one model's state workflow using an app-owned backed enum or validated string mapping and an explicit transition action. Keep persisted aliases, public strings and custom business work. Do not recreate state discovery, generic transition containers or unrelated workflows. Keep callers needing excluded features on their existing path. Preserve the upstream MIT notice when adapting source. Check get-recipe's current port catalog when considering alternatives. This guidance has not been exercised in your app; verify it with the checks below.
Source behaviour
In the inspected src/StateCaster.php, stored state values are morph names supplied by State::getMorphClass, which can be configured aliases or PHP class names. src/HasStates.php supplies initialization/creation defaults and state query scopes. Replacing a state object with a backed enum can change method calls and JSON serialization even when the database string stays identical.
src/State.php::transitionTo checks configured edges and resolves a transition; transition checks canTransition, invokes the handler through the container and dispatches StateChanged. Direct transition($transition) does not perform transitionTo's edge lookup. DefaultTransition::handle assigns/saves the model without itself wrapping the operation in a transaction or stale-write lock. Application/custom handler code may add those. StateConfig::ignoreSameState permits a self-edge; do not interpret that as a guarantee of no save/event.
Implementation
- Inventory stored aliases/class names, null/default policy, state subclasses/methods, configured and direct transitions, custom guards, scopes, model observers, events, jobs and resources. Select one finite graph. Map existing strings explicitly; unknown values fail rather than defaulting to an initial state. A native enum cast is suitable only when every stored value has a deliberate mapping and all former state-object consumers are migrated.
- Add one action beside existing application actions/services. Accept trusted actor/tenant separately from untrusted desired state and expected state/version. Replace dynamic transition selection with fixed app-owned code, retaining custom handler side effects deliberately. Enforcing configured edges on every entry point is a deliberate restriction compared with direct package transitions; review affected callers.
- In the existing connection's
DB::transaction, load the authorized model with the appropriate lock, recheck current ownership/guards and compare the caller's expected state or existing revision. Validate the allowed edge against this fresh state before assigning it. All writers must follow the same protocol; use driver-compatible serialization where row locks are unavailable. A UI's allowed-state list is not enforcement. - Save state and required audit/domain writes atomically, propagating exceptions. Eloquent
save()can return false when an observer vetoes it; explicitly throw on that result so the transaction rolls back rather than committing an audit-only success. Preserve needed observers if using Eloquent; raw query updates bypass model lifecycle hooks. Conditional updates must check affected-row count and all concurrency conditions. A state-only check cannot detect a leave-and-return cycle in cyclic graphs; use the app's existing monotonic revision where needed. New version columns or data rewrites need a separate rollout plan. - Emit app-owned success notifications and invalidate caches after commit, or use an existing outbox for durable external effects. This deliberately changes immediate package-event timing; inventory listeners and preserve their required payload/behaviour rather than merely renaming an event. Post-commit dispatch failure does not undo committed data. Handle retries with durable idempotency where effects require it, not a belief in exactly-once queues.
- Preserve transport error/status/resource output and replace used query scopes with explicit mapped values. Choose a same-state policy. The example rejects self-edges, deliberately unlike configurations allowing them. Remove the package only after all casts, transitions, state methods/scopes and listeners have replacements.
Complete pure predicate for an illustrative string-valued task graph. It uses no classes/imports and does not map stored legacy values, authorize, persist or run guards. Adapt its name/location to the existing action rather than installing a global helper:
function allows(string $from, string $to): bool
{
return match ($from) {
'queued' => in_array($to, ['running', 'cancelled'], true),
'running' => in_array($to, ['completed', 'cancelled'], true),
default => false,
};
}
Acceptance checklist
- For the example, accept only queued-to-running/cancelled and running-to-completed/cancelled. Reject queued-to-completed, completed-to-running, self-edges and unknown values. Use independently enumerated expectations for the application's real graph and every custom guard.
- Round-trip each existing alias/class-name state, default/null policy and API response. Required state-object methods and scope results remain available through their explicit replacements.
- Concurrent workers attempt queued-to-running and queued-to-cancelled with the same expected state: one commits, one conflicts, with one successful audit/event outcome. Use independent connections on the production driver, not one shared test transaction.
- Failure after the state write but before commit leaves original state/audit data visible from a fresh connection and emits no success notification. A post-commit delivery failure must not cause blind repetition of the committed business operation.
- HTTP/direct/job/command calls enforce required authorization and guards. Foreign tenants and revoked job-time permissions change nothing. Replayed jobs, custom handler work and any same-state behaviour match the declared contract.
Run the app's transition, observer, authorization, transaction and real queue-driver tests. Record PHP/Laravel/driver versions, outputs and deliberate changes. Search package state traits/casts/helpers and composer why spatie/laravel-model-states before removing the dependency.
Sources
- MIT reference source:
src/State.php,StateConfig.php,StateCaster.php,HasStates.php,Transition.php,DefaultTransition.php, andtests/TransitionTest.php. PreserveLICENSE.mdfor adapted code. - Framework source checked:
src/Illuminate/Database/Concerns/ManagesTransactions.php,Eloquent/Concerns/HasAttributes.php, andEloquent/Model.php; reconcile the metadata with the app's lockfile. - Port options: check
get-recipe's current port catalog (sourced from Package Port) at implementation time.