A quote in a business app looks like a simple record: a customer, some lines, a total, and a status column. Then one day someone finds an invoice that was created from a quote marked "rejected". Nobody can say how it got there. The UI hides the "Convert to order" button for rejected quotes, so it must have been something else: an old admin screen, an import script, a queue job that ran twice, or two people clicking at the same time.
The root cause is almost always the same. The status column is a free-text field that any code path can write to, and the rules about which status can follow which live in button visibility, not in the domain.
This post shows how I model document statuses in Laravel ERP and CRM apps so that the rules live in one place: a backed enum that knows its allowed transitions, a single service that performs every transition inside a locked transaction, a transition log, and a model guard that catches code paths that try to skip the service. The examples use Laravel 13 and PHP 8.3, and the enum logic below was run and checked before writing.
The problem: status as a string anyone can write
Here is what the status logic looks like in many codebases after a year:
<?php
// QuoteController
$quote->update(['status' => 'accepted']);
// ConvertQuoteJob
if ($quote->status !== 'converted') {
$quote->status = 'converted';
$quote->save();
}
// Nightly command
Quote::where('valid_until', '<', today())->update(['status' => 'expired']);
Three problems hide in these few lines:
-
No transition rules. Nothing stops
rejectedfrom becomingconverted, orconvertedgoing back todraft. - No history. When the status changes, the old value is gone. You cannot answer "who accepted this quote, and when?"
- Races. The job checks the status, then saves. If two workers (or a worker and a user) run at the same time, both can pass the check.
The nightly command has a fourth, quieter bug: it expires every quote past its date, including quotes that were already accepted or converted.
Step 1: A backed enum that knows its transitions
Start by making the set of statuses and the allowed moves between them explicit. A PHP backed enum is a good home for this, because the rules travel with the type:
<?php
namespace App\Enums;
enum QuoteStatus: string
{
case Draft = 'draft';
case Sent = 'sent';
case Accepted = 'accepted';
case Rejected = 'rejected';
case Expired = 'expired';
case Converted = 'converted';
/** @return list<self> */
public function allowedNext(): array
{
return match ($this) {
self::Draft => [self::Sent],
self::Sent => [self::Accepted, self::Rejected, self::Expired, self::Draft],
self::Accepted => [self::Converted],
self::Rejected, self::Expired => [self::Draft],
self::Converted => [],
};
}
public function canTransitionTo(self $to): bool
{
return in_array($to, $this->allowedNext(), true);
}
public function isFinal(): bool
{
return $this->allowedNext() === [];
}
}
The match expression has no default arm on purpose. If someone adds a new case and forgets to give it transitions, PHP throws an UnhandledMatchError the first time that status is used, instead of silently allowing nothing or everything.
Printed out, the map is short enough to review with the people who actually run the sales process:
draft --> sent
sent --> accepted | rejected | expired | draft
accepted --> converted
rejected --> draft
expired --> draft
converted --> (final)
That conversation matters more than the code. "Can an expired quote be reopened?" is a business decision. Once it is answered, it is written down in exactly one place.
Because the rules are plain PHP, they are trivial to test without a database:
<?php
use App\Enums\QuoteStatus;
it('allows only the documented transitions', function () {
expect(QuoteStatus::Draft->canTransitionTo(QuoteStatus::Sent))->toBeTrue()
->and(QuoteStatus::Draft->canTransitionTo(QuoteStatus::Converted))->toBeFalse()
->and(QuoteStatus::Converted->isFinal())->toBeTrue();
});
it('can reach every status from draft', function () {
$seen = [QuoteStatus::Draft];
$queue = [QuoteStatus::Draft];
while ($queue) {
foreach (array_shift($queue)->allowedNext() as $next) {
if (! in_array($next, $seen, true)) {
$seen[] = $next;
$queue[] = $next;
}
}
}
expect($seen)->toHaveCount(count(QuoteStatus::cases()));
});
The second test catches a status that nobody can ever reach, which usually means a transition was forgotten.
Step 2: Cast the column to the enum
Eloquent can cast an attribute to a backed enum. Add it to the model's casts method:
<?php
namespace App\Models;
use App\Enums\QuoteStatus;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable(['customer_id', 'currency', 'valid_until'])]
class Quote extends Model
{
protected function casts(): array
{
return [
'status' => QuoteStatus::class,
'valid_until' => 'immutable_date',
];
}
public function statusChanges(): HasMany
{
return $this->hasMany(QuoteStatusChange::class)->latest('id');
}
}
Now $quote->status is a QuoteStatus instance, comparisons are === against cases instead of string literals, and a typo like 'acepted' is no longer a valid value anywhere in your code. Reading an unknown value from the database fails loudly, because the cast uses the enum's from() method.
Note that status is not in the Fillable list. Status should never arrive through mass assignment from a request. It only changes through the service in the next step.
Step 3: One service performs every transition
Every status change goes through one class. It locks the row, checks the rule against the current database value, writes the new status and records the change, all in one transaction:
<?php
namespace App\Quotes;
use App\Enums\QuoteStatus;
use App\Models\Quote;
use App\Models\User;
use DomainException;
use Illuminate\Support\Facades\DB;
final class TransitionQuote
{
public function handle(Quote $quote, QuoteStatus $to, ?User $by, ?string $reason = null): Quote
{
return DB::transaction(function () use ($quote, $to, $by, $reason) {
/** @var Quote $locked */
$locked = Quote::query()->lockForUpdate()->findOrFail($quote->getKey());
$from = $locked->status;
if (! $from->canTransitionTo($to)) {
throw new DomainException(
"Quote {$locked->getKey()} cannot move from [{$from->value}] to [{$to->value}]."
);
}
$locked->status = $to;
$locked->save();
$locked->statusChanges()->create([
'from_status' => $from->value,
'to_status' => $to->value,
'changed_by' => $by?->getKey(),
'reason' => $reason,
]);
// QuoteStatusChange lists these four columns as Fillable.
return $locked;
}, 3);
}
}
The details that make this safe:
-
Re-read with
lockForUpdate(). The$quotepassed in may have been loaded seconds or minutes ago. The rule is checked against the row as it is now, and the lock makes a second request wait until the first one commits. The Laravel docs recommend wrapping pessimistic locks in a transaction for exactly this reason: the lock is held until the whole operation completes and released automatically on rollback. -
The second argument to
DB::transactionis the number of attempts if a deadlock occurs. -
Throw, don't return
false. A failed transition is an error the caller must handle, not a value it can ignore.
The log table is deliberately boring:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('quote_status_changes', function (Blueprint $table) {
$table->id();
$table->foreignId('quote_id')->constrained()->cascadeOnDelete();
$table->string('from_status', 20);
$table->string('to_status', 20);
$table->foreignId('changed_by')->nullable()->constrained('users');
$table->string('reason', 255)->nullable();
$table->timestamps();
$table->index(['quote_id', 'id']);
});
}
public function down(): void
{
Schema::dropIfExists('quote_status_changes');
}
};
changed_by is nullable because some transitions are made by the system, such as the nightly expiry. A null there means "automatic", which is worth showing as such in the UI.
Controllers become thin, and the exception turns into a normal validation-style error:
<?php
namespace App\Http\Controllers;
use App\Enums\QuoteStatus;
use App\Models\Quote;
use App\Quotes\TransitionQuote;
use DomainException;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class QuoteAcceptController extends Controller
{
public function __invoke(Request $request, Quote $quote, TransitionQuote $transition): RedirectResponse
{
$this->authorize('accept', $quote);
try {
$transition->handle($quote, QuoteStatus::Accepted, $request->user());
} catch (DomainException $e) {
return back()->withErrors(['status' => $e->getMessage()]);
}
return back()->with('success', 'Quote accepted.');
}
}
Step 4: A model guard for code that skips the service
The service only protects code that uses it. Six months from now someone will write $quote->status = QuoteStatus::Converted; $quote->save(); in a job. A model event can catch that. Register an updating closure in the model's booted method:
<?php
// inside App\Models\Quote
protected static function booted(): void
{
static::updating(function (Quote $quote) {
if (! $quote->isDirty('status')) {
return;
}
$from = QuoteStatus::from($quote->getRawOriginal('status'));
if (! $from->canTransitionTo($quote->status)) {
throw new \DomainException(
"Quote {$quote->getKey()} cannot move from [{$from->value}] to [{$quote->status->value}]."
);
}
});
}
isDirty('status') tells us the status is about to change, and getRawOriginal('status') gives the stored string from when the model was loaded, which we convert back with QuoteStatus::from(). Throwing inside updating stops the save before anything reaches the database.
This guard is a safety net, not the main mechanism. It checks against the value the model was loaded with, not a locked row, and it does not write the log. The service is still the only correct way to change status.
Step 5: Bulk transitions, done honestly
The nightly expiry is the one place where a mass update is tempting. Two things to know before writing it:
The Laravel docs are explicit that when you issue a mass update via Eloquent, the saving, saved, updating and updated model events are not fired, because the models are never retrieved. So the guard from Step 4 does not run, and no log rows are written.
If you do use a mass update, make the WHERE clause carry the transition rule itself:
<?php
use App\Enums\QuoteStatus;
use App\Models\Quote;
$expired = Quote::query()
->where('status', QuoteStatus::Sent)
->where('valid_until', '<', today())
->update(['status' => QuoteStatus::Expired->value]);
Filtering on status = sent fixes the original bug: accepted and converted quotes are never touched, and a quote that someone accepts at the same moment no longer matches. But you still lose the history.
For most ERP volumes, I prefer to run each quote through the service in chunks. It is slower and completely worth it:
<?php
namespace App\Console\Commands;
use App\Enums\QuoteStatus;
use App\Models\Quote;
use App\Quotes\TransitionQuote;
use DomainException;
use Illuminate\Console\Command;
class ExpireQuotes extends Command
{
protected $signature = 'quotes:expire';
public function handle(TransitionQuote $transition): int
{
Quote::query()
->where('status', QuoteStatus::Sent)
->where('valid_until', '<', today())
->lazyById(200)
->each(function (Quote $quote) use ($transition) {
try {
$transition->handle($quote, QuoteStatus::Expired, null, 'Validity date passed');
} catch (DomainException) {
// Status changed since the query ran (for example, accepted). Skip it.
}
});
return self::SUCCESS;
}
}
lazyById pages by primary key, which the docs recommend when you update the records you are iterating over. Each quote is locked, re-checked and logged individually.
Common pitfalls
Comparing enum cases with strings. After adding the cast, $quote->status === 'sent' is always false, because the attribute is now an enum instance. Search the codebase for string comparisons on status when you introduce the cast.
Putting the rules in the frontend. Hiding the button is good UX. It is not a rule. The rule is canTransitionTo(), and the UI can call it too: expose allowedNext() to your Inertia or API response and render only the actions the backend would accept.
Checking the old in-memory status. if ($quote->status === QuoteStatus::Sent) on a model loaded earlier in the request is the race from the opening story. Check against the locked row.
Side effects inside the transaction. If accepting a quote sends an email or calls another system, do not do it inside DB::transaction. Dispatch a job after commit (the queue's afterCommit option) so a rolled-back transition never sends anything.
Renaming enum values. The backing values ('sent', 'accepted') are stored in the database and in the log. Treat them like column names: rename the case if you like, but change the stored value only with a data migration.
One enum for every document. Quotes, orders and invoices have different lifecycles. Give each document type its own enum and its own map, even if some statuses share names.
Summary
- Model each document's statuses as a backed enum with an explicit
allowedNext()map and nodefaultarm. - Cast the column to the enum and keep
statusout of mass assignment. - Perform every transition in one service: lock the row, check the rule against the current value, update, and write a log row in the same transaction.
- Add an
updatingmodel guard as a safety net for code that bypasses the service. - Remember that mass updates skip model events; filter on the current status, or run bulk changes through the service in chunks.
The result is boring in the best way: when someone asks "how did this rejected quote become an order?", the answer is either "it can't" or a row in the log with a name and a timestamp.
How do you handle document status rules in your apps: in the model, in a service, or with a state machine package?
Top comments (0)