Skip to content

Lesson 3 of 22 · Queries and Data Access

Laravel Eager Loading From the Model

Intermediate•
lesson•
November 30, 2026•
~4 min read

The Reservation model from the last lesson carries the line protected $with = ['guest', 'room'];. Someone added it for the reservation detail page, which reads the guest and the room, and it stayed. Since then every query that returns a Reservation model has loaded the guest and the room along with it, whether the calling code wanted them or not.

A query that pays for nothing

The front desk records a payment against a reservation. The controller loads the reservation by id, creates the payment, and redirects.

PHP
<?php declare(strict_types=1); namespace App\Http\Controllers; use App\Models\Reservation; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Carbon; class PaymentController extends Controller { public function store(Request $request, int $reservationId): RedirectResponse { $request->validate([ 'amount_cents' => 'required|integer|min:1', ]); $reservation = Reservation::query()->findOrFail($reservationId); $reservation->payments()->create([ 'amount_cents' => $request->integer('amount_cents'), 'captured_at' => Carbon::now(), ]); return redirect()->route('reservations.show', $reservation); } }

The query log for one payment:

SQL
select * from `reservations` where `reservations`.`id` = ? limit 1 select * from `guests` where `guests`.`id` in (12) select * from `rooms` where `rooms`.`id` in (31) insert into `payments` (`amount_cents`, `captured_at`, `reservation_id`, `updated_at`, `created_at`) values (?, ?, ?, ?, ?)

Two of those four queries fetch rows this controller never reads. Nothing in the file mentions a guest or a room, so nothing in the file explains the cost. You read findOrFail() and assume one lookup.

Where $with costs and where it does not

$with is run by Builder::get(). The builder runs the main query, hydrates the rows into models, and then, if there is at least one model, calls eagerLoadRelations() on the set. Every method that finishes with a get() pays: get(), first(), find(), findOrFail(), all(), paginate(), and each batch of chunk(). If the same line sat on your User model, the auth guard's per-request lookup of the logged-in user would pay it on every authenticated request.

Aggregates do not pay. count(), exists(), sum(), and max() are in the builder's pass-through list, and a pass-through method runs on toBase(), the plain query builder underneath Eloquent. No rows are hydrated, so there is nothing to eager load. pluck() also goes through toBase(), and only maps the values through the model's casts and accessors. So the dashboard's Reservation::query()->where('status', 'confirmed')->count() is one query, $with or not.

The rule of thumb: if a call returns model instances, $with runs. If it returns a number, a boolean, or a plain collection of values, it does not.

Why it hurts

The cost is paid by code that never opted in. The detail page that needed both relations is fine. Every other read of a reservation, the payment endpoint, the check-in lookup by confirmation code, the nightly job that walks tomorrow's arrivals, now runs three queries where it needed one, and the extra two are invisible at the call site.

It also grows. Add payments to the list because a new screen needs it and every reservation read in the application widens again, including the ones inside loops. A $with on a model with a thousand call sites is a change to a thousand queries, and nobody reviewing the pull request sees a single one of them.

Load at the query site

Remove the line from the model.

PHP
<?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 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 page that needs the relations asks for them where it builds the query. The detail page shows the guest, the room, and the room type's name, so it loads all three.

PHP
<?php declare(strict_types=1); namespace App\Http\Controllers; use App\Models\Reservation; use Illuminate\View\View; class ReservationController extends Controller { public function show(int $reservationId): View { $reservation = Reservation::query() ->with(['guest', 'room.roomType']) ->findOrFail($reservationId); return view('reservations.show', ['reservation' => $reservation]); } }

The other actions are unchanged.

Four queries, one per table, and all four are visible in the method that needs them. PaymentController is unchanged and now runs one SELECT and one INSERT.

When a screen changes, the with() next to it changes, and the diff shows both.

The one thing to remember

$with on the model is a cost every model-returning query pays, and no call site can see it. Put with() next to the query that reads the relation.

Course Content