Skip to content

Don't Fix a Lazy Loading Exception With with()

Quick Tips•
November 23, 2026

With Model::shouldBeStrict() on, filtering guests by their reservations in a closure throws a LazyLoadingViolationException on the first guest. The query returned several guests, so each one carries the lazy loading guard, and reading $guest->reservations would have run one query per guest. The obvious fix is with('reservations'). It silences the exception and keeps the cost: the page now loads every guest and every reservation the property has ever taken, to find the few guests who stayed more than twice.

Don't do this:

PHP
<?php declare(strict_types=1); namespace App\Guests; use App\Models\Guest; use Illuminate\Database\Eloquent\Collection; final readonly class ReturningGuests { /** * @return Collection<int, Guest> */ public function get(): Collection { return Guest::query() ->with('reservations') ->get() ->filter(fn (Guest $guest): bool => $guest->reservations->where('status', 'confirmed')->count() > 2) ->values(); } }

Do this instead:

PHP
<?php declare(strict_types=1); namespace App\Guests; use App\Models\Guest; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; final readonly class ReturningGuests { /** * @return Collection<int, Guest> */ public function get(): Collection { return Guest::query() ->whereHas( 'reservations', fn (Builder $query): Builder => $query->where('status', 'confirmed'), '>', 2, ) ->get(); } }

whereHas() takes the relation, a closure that constrains it, an operator, and a count. Eloquent turns it into where (select count(*) from reservations where ...) > 2, so the database counts per guest and PHP builds models only for the guests who qualify. No relation is loaded, so strict mode has nothing to object to.

Read the exception as a pointer to work the database should be doing. with() is the right fix when the page displays each guest's reservations. It is the wrong one when the code only counts them.