Lesson 4 of 22 · Queries and Data Access
Laravel Accessors That Run Queries
One accessor on the Reservation model is left over from the last two lessons. outstandingBalance() returns Attribute::make() with a getter of $this->total_cents - (int) $this->payments()->sum('amount_cents'). It reads as a property, and the front desk's arrivals list uses it as one.
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Reservation;
use Illuminate\Support\Carbon;
use Illuminate\View\View;
class DashboardController extends Controller
{
public function __invoke(): View
{
$arrivals = Reservation::query()
->whereDate('check_in', Carbon::today())
->with(['guest', 'room'])
->orderBy('check_in')
->get();
return view('dashboard', ['arrivals' => $arrivals]);
}
}@foreach ($arrivals as $reservation)
<tr>
<td>{{ $reservation->guest->name }}</td>
<td>{{ $reservation->room->number }}</td>
<td>{{ number_format($reservation->outstanding_balance / 100, 2) }}</td>
</tr>
@endforeachOpen Debugbar on a day with forty arrivals. Three queries for the reservations, guests, and rooms, then forty more that differ only in one bound value:
select sum(`amount_cents`) as `aggregate` from `payments` where `payments`.`reservation_id` = ? and `payments`.`reservation_id` is not nullEach read of $reservation->outstanding_balance runs the accessor, and the accessor runs $this->payments()->sum(), which is a query.
Why it survives review
This is the N+1 that gets past review, because the query is not in the controller. The controller eager loads its relations and looks careful. The Blade template reads a property. The accessor is a few lines in a model file nobody opens for a dashboard change. No single query is slow, so the slow query log stays quiet, and the page cost grows in step with the number of arrivals.
The page was fine in development with three seeded reservations. It is forty extra queries on an ordinary day.
Strict mode does not catch this
Laravel can throw on lazy loading. Turn it on in AppServiceProvider:
<?php
declare(strict_types=1);
namespace App\Providers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\ServiceProvider;
final class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
Model::shouldBeStrict();
}
}shouldBeStrict() turns on three guards: preventLazyLoading, preventSilentlyDiscardingAttributes, and preventAccessingMissingAttributes. The first one throws a LazyLoadingViolationException when code reads a relation that was not eager loaded, on a model that came back as part of a set of more than one. The builder's hydrate() sets the flag only when the result had more than one row, so a single find() followed by $reservation->guest still works, and a loop over forty reservations reading $reservation->guest without with('guest') throws on the first one. If throwing in production worries you, pass ! $this->app->isProduction() to shouldBeStrict(). I leave it on everywhere, because a lazy load in production is a bug I want to hear about.
It does nothing for the accessor above. The guard lives in getRelationValue(), the code path for reading a relation as a property. $this->payments()->sum() calls the relation method and runs a query through it, and that path has no guard. An accessor is free to run any query it likes and strict mode will never hear about it.
Compute it in the query
Ask the database for the paid total once, alongside the reservations, and let the model do arithmetic on what is already in memory. withSum() adds a subselect column to the main query.
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Reservation;
use Illuminate\Support\Carbon;
use Illuminate\View\View;
class DashboardController extends Controller
{
public function __invoke(): View
{
$arrivals = Reservation::query()
->whereDate('check_in', Carbon::today())
->with(['guest', 'room'])
->withSum('payments as paid_cents', 'amount_cents')
->orderBy('check_in')
->get();
return view('dashboard', ['arrivals' => $arrivals]);
}
}The accessor goes. In its place, a method that reads the loaded column.
<?php
declare(strict_types=1);
namespace App\Models;
use App\Traits\CalculatesPrice;
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 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);
}
public function outstandingCents(): int
{
return $this->total_cents - (int) $this->paid_cents;
}
}@foreach ($arrivals as $reservation)
<tr>
<td>{{ $reservation->guest->name }}</td>
<td>{{ $reservation->room->number }}</td>
<td>{{ number_format($reservation->outstandingCents() / 100, 2) }}</td>
</tr>
@endforeachThree queries for forty arrivals, and the same three for four hundred. paid_cents is null for a reservation with no payments, so the cast to int stays.
Making it a method instead of an accessor is deliberate. $reservation->outstanding_balance promised a property and hid a query. $reservation->outstandingCents() is a call, and a call is allowed to have a precondition: the query must have loaded paid_cents. Strict mode enforces that precondition for free. With preventAccessingMissingAttributes on, reading $this->paid_cents on a reservation loaded from the database without withSum() throws a MissingAttributeException that names the attribute, instead of returning null and quietly reporting the full total as outstanding.
The one thing to remember
An accessor formats what is already in memory. Anything that needs another table is loaded by the query, with with() or withSum(), and read by a method whose precondition strict mode can check.