Lesson 2 of 22 · Queries and Data Access
Laravel Observers: Saving the Same Reservation Four Times
Turn on the query log (Laravel Debugbar, or DB::enableQueryLog() in a tinker session) and submit the reservation form once. One POST /reservations, and the write statements in the log are these:
insert into `reservations` (`guest_id`, `room_id`, `check_in`, `check_out`, `adults`, `children`, `status`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?, ?, ?, ?, ?)
update `reservations` set `guest_id` = ?, `room_id` = ?, `check_in` = ?, `check_out` = ?, `adults` = ?, `children` = ?, `status` = ?, `created_at` = ?, `id` = ?, `confirmed_at` = ?, `reservations`.`updated_at` = ? where `id` = ?
update `reservations` set `confirmation_code` = ?, `reservations`.`updated_at` = ? where `id` = ?
update `reservations` set `total_cents` = ?, `reservations`.`updated_at` = ? where `id` = ?One reservation, four writes: an insert and three updates. store() from the introduction accounts for two of them: the create() and the save() after the total is calculated. The other two come from files the controller never mentions.
Where the other writes come from
The model declares both of them. Here is Reservation as it stands today, with everything in it, because the next two lessons each pick on a different line.
<?php
declare(strict_types=1);
namespace App\Models;
use App\Events\ReservationCreated;
use App\Observers\ReservationObserver;
use App\Traits\CalculatesPrice;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[ObservedBy(ReservationObserver::class)]
class Reservation extends Model
{
use CalculatesPrice;
protected $fillable = [
'guest_id', 'room_id', 'check_in', 'check_out', 'adults', 'children',
'status', 'total_cents', 'confirmation_code', 'confirmed_at',
];
protected $with = ['guest', 'room'];
protected $dispatchesEvents = [
'created' => ReservationCreated::class,
];
protected function casts(): array
{
return [
'check_in' => 'immutable_date',
'check_out' => 'immutable_date',
'confirmed_at' => 'immutable_datetime',
];
}
public function guest(): BelongsTo
{
return $this->belongsTo(Guest::class);
}
public function room(): BelongsTo
{
return $this->belongsTo(Room::class);
}
public function payments(): HasMany
{
return $this->hasMany(Payment::class);
}
protected function outstandingBalance(): Attribute
{
return Attribute::make(
get: fn (): int => $this->total_cents - (int) $this->payments()->sum('amount_cents'),
);
}
}The #[ObservedBy] attribute registers an observer. Its created hook sets the confirmation code and saves.
<?php
declare(strict_types=1);
namespace App\Observers;
use App\Models\Reservation;
use Illuminate\Support\Str;
class ReservationObserver
{
public function created(Reservation $reservation): void
{
$reservation->confirmation_code = Str::upper(Str::random(8));
$reservation->save();
}
}$dispatchesEvents maps the same created hook to a ReservationCreated event class, which Eloquent builds with new ReservationCreated($reservation).
<?php
declare(strict_types=1);
namespace App\Events;
use App\Models\Reservation;
final class ReservationCreated
{
public function __construct(public Reservation $reservation)
{
}
}A listener, which Laravel discovers from the type-hint on its handle() method, confirms the reservation and saves.
<?php
declare(strict_types=1);
namespace App\Listeners;
use App\Events\ReservationCreated;
use Illuminate\Support\Carbon;
class SendReservationConfirmation
{
public function handle(ReservationCreated $event): void
{
$reservation = $event->reservation;
$reservation->status = 'confirmed';
$reservation->confirmed_at = Carbon::now();
$reservation->save();
}
}Eloquent has not synced the model's original attributes yet when created fires, so the listener's save rewrites every column.
Nobody built it this way on purpose. The observer went in because observers felt like the Laravel way to react to a save. The listener went in so the controller could stay thin. Each decision was small, and together they spread one write across three files that do not know about each other.
Why it hurts
Which update runs first? Read the log again: the listener's status update lands before the observer's confirmation_code update, although the observer was registered on the model and the listener was not. The order is decided inside Eloquent's fireModelEvent(), which dispatches the $dispatchesEvents class first and only then fires the string event that observers subscribe to. To know what row a reservation ends up as, you have to know that.
Each of the four statements runs on its own, with the database committing after every one, because nothing wraps them in a transaction. Any of them can fail on its own. The last write is the total_cents update, and it is the one most likely to fail: calculateTotalCents() reads $this->room->roomType->nightly_rate_cents, and a room whose type was soft-deleted returns null and throws. When that happens the reservation already exists, is already confirmed, already has a confirmation code, and has no total. The front desk sees a confirmed reservation with no price to collect.
For the import, this shape is a dead end. The command would have to create the reservation, then know that two hidden writes fire, then set the total, and none of that is written down anywhere the importer could read it.
One use case, one write
Compute everything the reservation needs before the insert, then insert once. The confirmation code is a random string, the total needs the room's rate, and the status is a fact the controller already knows.
The listener was confirming every reservation the instant it was created, so nothing in this codebase was ever pending. That is the actual rule of the property: a web reservation is confirmed on submission. The fix writes that rule where it can be read.
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Mail\ReservationConfirmation;
use App\Models\Reservation;
use App\Models\Room;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
class ReservationController extends Controller
{
public function store(Request $request): RedirectResponse
{
$request->validate([
'room_id' => 'required|exists:rooms,id',
'check_in' => 'required|date|after_or_equal:today',
'check_out' => 'required|date|after:check_in',
'adults' => 'required|integer|min:1',
'children' => 'required|integer|min:0',
]);
$guest = Auth::user()->guest;
$room = Room::query()->with('roomType')->findOrFail($request->integer('room_id'));
$reservation = new Reservation([
'guest_id' => $guest->id,
'room_id' => $room->id,
'check_in' => $request->input('check_in'),
'check_out' => $request->input('check_out'),
'adults' => $request->integer('adults'),
'children' => $request->integer('children'),
'status' => 'confirmed',
'confirmed_at' => Carbon::now(),
'confirmation_code' => Str::upper(Str::random(8)),
]);
$reservation->setRelation('room', $room);
$reservation->total_cents = $reservation->calculateTotalCents();
$reservation->save();
Mail::to($guest->email)->send(new ReservationConfirmation($reservation));
return redirect()->route('reservations.show', $reservation);
}
}The other actions are unchanged.
new Reservation([...]) followed by one save() is one INSERT. The room is loaded up front with its type, and setRelation() hands it to the model so calculateTotalCents() reads it without a query of its own. If the rate lookup throws, it throws before anything is written, so no confirmed reservation is left without a price.
Delete ReservationObserver, SendReservationConfirmation, and the ReservationCreated event. Remove the #[ObservedBy] attribute and $dispatchesEvents from the model. The rest of the model stays as it was for now, $with and the accessor included.
<?php
declare(strict_types=1);
namespace App\Models;
use App\Traits\CalculatesPrice;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Reservation extends Model
{
use CalculatesPrice;
protected $fillable = [
'guest_id', 'room_id', 'check_in', 'check_out', 'adults', 'children',
'status', 'total_cents', 'confirmation_code', 'confirmed_at',
];
protected $with = ['guest', 'room'];
protected function casts(): array
{
return [
'check_in' => 'immutable_date',
'check_out' => 'immutable_date',
'confirmed_at' => 'immutable_datetime',
];
}
public function guest(): BelongsTo
{
return $this->belongsTo(Guest::class);
}
public function room(): BelongsTo
{
return $this->belongsTo(Room::class);
}
public function payments(): HasMany
{
return $this->hasMany(Payment::class);
}
protected function outstandingBalance(): Attribute
{
return Attribute::make(
get: fn (): int => $this->total_cents - (int) $this->payments()->sum('amount_cents'),
);
}
}The query log for the same POST now shows one INSERT.
When a transaction earns its place
One insert is atomic on its own, so this version does not need DB::transaction(). A transaction earns its place when a use case genuinely writes two rows that must commit together: a reservation and the payment authorization that guarantees it, for example. Wrap those two in one transaction and either both exist or neither does.
That is different from what the observer and listener were doing. They were not writing a second row. They were finishing the first one, in two other files, after the insert had already committed. No transaction fixes that, because the problem was never atomicity.
Observers and listeners are for side effects: sending the mail, updating a dashboard counter, telling housekeeping.
The one thing to remember
Decide every column before the insert and write the row once. If a hook has to save the row that fired it, the write is in the wrong place.