Skip to content

Lesson 5 of 22 · Queries and Data Access

Laravel Query Builder for Reports, Not Eloquent Loops

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

The dashboard has a second block under the arrivals list: occupancy for the month, one row per room type, with nights sold and revenue. It is built the way the reservations list is built, because that is the only way this codebase has ever built anything.

PHP
<?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(); $start = Carbon::today()->startOfMonth(); $end = Carbon::today()->endOfMonth(); $reservations = Reservation::query() ->where('status', 'confirmed') ->whereBetween('check_in', [$start, $end]) ->with('room.roomType') ->get(); $occupancy = []; foreach ($reservations as $reservation) { $type = $reservation->room->roomType->name; $occupancy[$type]['nights'] = ($occupancy[$type]['nights'] ?? 0) + $reservation->check_in->diffInDays($reservation->check_out); $occupancy[$type]['revenue_cents'] = ($occupancy[$type]['revenue_cents'] ?? 0) + $reservation->total_cents; } ksort($occupancy); return view('dashboard', [ 'arrivals' => $arrivals, 'occupancy' => $occupancy, ]); } }

It reads like a tutorial: load the records, loop, add up. It produces two numbers per room type. To do that it loads every confirmed reservation in the month, every room those reservations point at, and every room type behind those rooms, into memory, as models.

What a model costs

Every row Eloquent returns becomes a full model object. Each date you read becomes a CarbonImmutable, and the loop reads two per reservation. Each model registers its loaded relations. For a busy month that is one Reservation object per stay, plus the Room and RoomType objects behind them, allocated to produce a table that fits on an index card.

The arithmetic is also in the wrong place. The database can group and sum a month of rows in one query. The foreach sums them one at a time, in PHP, after paying to build objects it reads once and discards.

None of this shows on a seed database, and all of it shows once the property has real history behind it and the dashboard is the first page every manager opens in the morning.

Ask the database for the answer

Eloquent is for the rows you create and change. A report is a question, and the query builder answers questions without building models. Give the report a class of its own, so the query has a name, a home, and a place to be tested.

PHP
<?php declare(strict_types=1); namespace App\Reports; final readonly class OccupancyRow { public function __construct( public string $roomType, public int $nights, public int $revenueCents, ) { } }
PHP
<?php declare(strict_types=1); namespace App\Reports; use Illuminate\Database\ConnectionInterface; use Illuminate\Support\Carbon; final readonly class OccupancyReport { public function __construct(private ConnectionInterface $connection) { } /** * @return list<OccupancyRow> */ public function forMonth(int $year, int $month): array { $start = Carbon::create($year, $month, 1)->startOfMonth(); $end = $start->copy()->endOfMonth(); $rows = $this->connection->table('reservations') ->join('rooms', 'rooms.id', '=', 'reservations.room_id') ->join('room_types', 'room_types.id', '=', 'rooms.room_type_id') ->where('reservations.status', 'confirmed') ->whereBetween('reservations.check_in', [$start, $end]) ->groupBy('room_types.name') ->orderBy('room_types.name') ->select('room_types.name as room_type') ->selectRaw('SUM(DATEDIFF(reservations.check_out, reservations.check_in)) as nights') ->selectRaw('SUM(reservations.total_cents) as revenue_cents') ->get(); return $rows ->map(fn (object $row): OccupancyRow => new OccupancyRow( roomType: $row->room_type, nights: (int) $row->nights, revenueCents: (int) $row->revenue_cents, )) ->all(); } }

DATEDIFF is MySQL. On Postgres the same line is SUM(reservations.check_out - reservations.check_in). On SQLite it is SUM(julianday(reservations.check_out) - julianday(reservations.check_in)). That is the trade you make when the SQL is the point: you write the SQL for the database you run.

ConnectionInterface is Laravel's contract for a database connection, and the container hands you the default one when you type-hint it. The report asks for it in the constructor instead of calling the DB facade, so a test can hand it the test connection and a reader can see from the signature that this class talks to the database.

The controller injects the report.

PHP
<?php declare(strict_types=1); namespace App\Http\Controllers; 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() ->whereDate('check_in', $today) ->with(['guest', 'room']) ->withSum('payments as paid_cents', 'amount_cents') ->orderBy('check_in') ->get(); return view('dashboard', [ 'arrivals' => $arrivals, 'occupancy' => $this->occupancy->forMonth($today->year, $today->month), ]); } }
BLADE
@foreach ($occupancy as $row) <tr> <td>{{ $row->roomType }}</td> <td>{{ $row->nights }}</td> <td>{{ number_format($row->revenueCents / 100, 2) }}</td> </tr> @endforeach

One query returns one row per room type, already summed. The map() turns each plain row into an OccupancyRow, a small class whose only job is to give the three values names and types, so the Blade template reads $row->nights instead of $row['nights'], and your editor and PHPStan can flag a misspelled property, which they cannot do for an array key. An array of those rows is the right return type for a report. There is no behaviour to attach and nothing to save.

app/Reports is the first folder in this codebase named after a job instead of a kind of file. It is there because a report is neither a controller nor a model, and app/Services in this codebase is where code goes to lose its name. A later lesson has more to say about folders. For now, notice that the query got a name the moment it got a class.

What you give up

Dropping to the query builder means giving up casts, accessors, model events, and relations. A report needs none of them. It needs a fast, correct aggregation and a typed result.

The one thing to remember

Eloquent is for the rows a use case changes. When the query is the product, write the query, give it a class, and return typed rows.

Course Content