Lesson 7 of 22 · Queries and Data Access
Laravel whereHas Instead of a Collection Filter
The dashboard has one more widget: returning guests, the people with more than two confirmed stays, so the desk can greet them by name. It was added in an afternoon and it looks like this. Guest has a reservations(): HasMany relation, and the widget reads it for every guest.
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Guest;
use App\Models\Reservation;
use App\Reports\OccupancyReport;
use Illuminate\Support\Carbon;
use Illuminate\View\View;
class DashboardController extends Controller
{
public function __construct(private OccupancyReport $occupancy)
{
}
public function __invoke(): View
{
$today = Carbon::today();
$arrivals = Reservation::query()
->select(['id', 'guest_id', 'room_id', 'total_cents'])
->whereDate('check_in', $today)
->with(['guest:id,name', 'room:id,number'])
->withSum('payments as paid_cents', 'amount_cents')
->orderBy('check_in')
->get();
$returning = Guest::all()
->filter(fn (Guest $guest): bool => $guest->reservations->where('status', 'confirmed')->count() > 2)
->sortBy('name');
return view('dashboard', [
'arrivals' => $arrivals,
'occupancy' => $this->occupancy->forMonth($today->year, $today->month),
'returning' => $returning,
]);
}
}Since the accessor fix turned on Model::shouldBeStrict(), this widget no longer renders. Guest::all() returns more than one guest, so each one carries the lazy-loading flag, and the first $guest->reservations inside the closure throws a LazyLoadingViolationException. Strict mode did its job: it turned a silent N+1 into an error with a class name in it. Before strict mode, the same line ran one query per guest in the table, every time anyone opened the dashboard.
The fix strict mode invites, adding Guest::with('reservations')->get(), stops the exception and keeps the mistake. Now the page loads every guest and every reservation the property has ever taken, into memory, to find the dozen guests who qualify.
What all() does before the filter runs
Guest::all() pulls every row out of the table and builds a model for each. Only then does filter() walk that collection in PHP and discard the guests who do not qualify. You loaded the whole table to keep a fraction of it, and the fraction is the only part the page shows.
The database was built to answer "guests with more than two confirmed reservations". It can count reservations per guest in one query. Filtering in a collection throws that away.
The cost grows with the size of the table. Memory: every guest becomes a hydrated model, and with the with('reservations') fix, so does every reservation. Time: the database serialises the whole result, ships it, and PHP deserialises all of it before the first filter() call. The page that returned in an instant against forty seeded guests reads the whole history of the property against real data, and the code is identical to the day it shipped.
There is a quieter cost. The collection's where() and the query builder's where() look the same. Guest::where('name', 'like', 'A%')->get() filters in SQL; Guest::all()->where('name', 'A') filters in PHP. The closure above uses the collection version on $guest->reservations, and a reader skimming it sees a where and assumes a query. Code that mixes the two trains everyone reading it to stop noticing which is which.
Push the predicate into the query
whereHas() takes an operator and a count, so the whole question becomes one query.
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Guest;
use App\Models\Reservation;
use App\Reports\OccupancyReport;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Illuminate\View\View;
class DashboardController extends Controller
{
public function __construct(private OccupancyReport $occupancy)
{
}
public function __invoke(): View
{
$today = Carbon::today();
$arrivals = Reservation::query()
->select(['id', 'guest_id', 'room_id', 'total_cents'])
->whereDate('check_in', $today)
->with(['guest:id,name', 'room:id,number'])
->withSum('payments as paid_cents', 'amount_cents')
->orderBy('check_in')
->get();
$returning = Guest::query()
->select(['id', 'name'])
->whereHas(
'reservations',
fn (Builder $query): Builder => $query->where('status', 'confirmed'),
'>',
2,
)
->orderBy('name')
->get();
return view('dashboard', [
'arrivals' => $arrivals,
'occupancy' => $this->occupancy->forMonth($today->year, $today->month),
'returning' => $returning,
]);
}
}select `id`, `name` from `guests` where (select count(*) from `reservations` where `guests`.`id` = `reservations`.`guest_id` and `status` = ?) > 2 order by `name` ascOne query. The database counts per guest, keeps the ones over two, sorts, and returns a dozen rows with two columns each. PHP hydrates a dozen Guest models instead of the whole table and its history.
If the widget also shows the number of stays, keep the whereHas() and add withCount(['reservations as confirmed_stays' => fn (Builder $query): Builder => $query->where('status', 'confirmed')]). The count becomes a column, the filter still runs in the database, and $guest->confirmed_stays is there for the template to read. The Builder type-hint in these closures is Illuminate\Database\Eloquent\Builder.
The same move covers the other forms this mistake takes. Reservation::all()->where('status', 'cancelled') becomes Reservation::query()->where('status', 'cancelled')->get(). ->sortByDesc('created_at')->take(20) on a collection becomes ->latest()->limit(20) on the query, and the database applies the limit before sending anything. A filter() that checks a related row becomes a whereHas().
Where the query lessons leave the code
Every query on the dashboard and in store() now says what it reads and lets the database do the work it was built for.
What has not changed is the shape of the code around those queries. ReservationController still validates inline, still reaches for Auth::user(), still sends mail from the middle of store(), and the pricing rule still lives in a trait. The import from the introduction is no closer to reusing any of it. That is the next chapter.
The one thing to remember
If a collection that came from all() is being filtered, sorted, or counted in PHP, the question belongs in the query. Move it there and the cost stops tracking the size of the table.