Lesson 26 of 45 · Commands and Queries
Queries and Query Handlers
Five fields from a full entity
The booking detail page shows a reservation's guest name, room number, check-in and check-out dates, status and total. The controller loads it the way the repository lesson taught: $this->reservations->withId($id) returns a Reservation, and the template reads what it needs.
That works, and it does wasteful things. The repository maps every column into value objects. The entity carries its recorded events and its rules about cancelling and checking in, and the page uses none of them. The guest's name and the room number aren't on Reservation at all. The repository lesson's pitfall "Using the repository for screens and reports" said to query straight into a small read DTO for this kind of page. This lesson builds that.
The query, the handler and the read DTO
A query mirrors a command from the previous lesson: an object that holds the input, and a handler that does the work. Three classes make up the read side of this page.
ReservationSummaryQuery holds the input, which is the id of the reservation to show.
<?php
declare(strict_types=1);
namespace App\Reservations;
final readonly class ReservationSummaryQuery
{
public function __construct(
public ReservationId $reservationId,
) {}
}ReservationSummary is the read DTO from the Data Transfer Objects lesson applied to output. It has one field per thing on the screen and no methods that decide anything. It reuses Money from the Value Objects lesson and the ReservationStatus enum, so the template doesn't format raw cents.
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Billing\Money;
use DateTimeImmutable;
final readonly class ReservationSummary
{
public function __construct(
public ReservationId $reservationId,
public string $guestName,
public string $roomNumber,
public DateTimeImmutable $checkIn,
public DateTimeImmutable $checkOut,
public ReservationStatus $status,
public Money $totalPrice,
) {}
}The handler reads the data with Laravel's query builder. It takes Illuminate\Database\ConnectionInterface, which the container resolves, and doesn't touch the Reservations repository. The schema here is assumed: guests.full_name and rooms.number are columns this course hasn't shown, next to the reservations columns from the repository's save().
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Billing\Currency;
use App\Billing\Money;
use App\Reservations\Exceptions\ReservationNotFound;
use DateTimeImmutable;
use Illuminate\Database\ConnectionInterface;
final readonly class ReservationSummaryQueryHandler
{
public function __construct(private ConnectionInterface $connection) {}
public function handle(ReservationSummaryQuery $query): ReservationSummary
{
$row = $this->connection->table('reservations')
->join('guests', 'guests.id', '=', 'reservations.guest_id')
->join('rooms', 'rooms.id', '=', 'reservations.room_id')
->where('reservations.id', $query->reservationId->value)
->first([
'guests.full_name as guest_name',
'rooms.number as room_number',
'reservations.check_in',
'reservations.check_out',
'reservations.status',
'reservations.price_cents',
'reservations.currency',
]);
if ($row === null) {
throw new ReservationNotFound($query->reservationId);
}
return new ReservationSummary(
reservationId: $query->reservationId,
guestName: $row->guest_name,
roomNumber: $row->room_number,
checkIn: new DateTimeImmutable($row->check_in),
checkOut: new DateTimeImmutable($row->check_out),
status: ReservationStatus::from($row->status),
totalPrice: Money::fromCents((int) $row->price_cents, new Currency($row->currency)),
);
}
}The controller shrinks to the shape of CheckOutGuestController, with the DTO going to the view.
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Reservations\ReservationId;
use App\Reservations\ReservationSummaryQuery;
use App\Reservations\ReservationSummaryQueryHandler;
use Illuminate\Contracts\View\View;
final class ReservationSummaryController
{
public function __invoke(string $reservationId, ReservationSummaryQueryHandler $handler): View
{
$summary = $handler->handle(new ReservationSummaryQuery(new ReservationId($reservationId)));
return view('reservations.summary', ['summary' => $summary]);
}
}What goes in the DTO
Put in the DTO what the screen shows, typed. ReservationSummary holds a Money and a ReservationStatus, and the template decides how to print them: $summary->totalPrice through a formatter, the status through a label. Formatting belongs to the view, so the DTO doesn't hold a string like "EUR 420.00". A second screen that wants the amount in cents, or the status as a badge, would then have to parse it back.
The DTO is also where the join shows up. guestName and roomNumber come from other tables, and the handler fetched them in the same query. The handler's first() call is the only query this page makes.
Testing is plain too. A test for the handler seeds a reservation, a guest and a room in a test database, runs the handler and asserts the fields of the DTO. It doesn't need a clock, an event dispatcher or a repository, because the handler has none of them. The inserts list only the columns this lesson assumes; a real schema will want more. The test also needs migrations for the guests and rooms tables, which no lesson shows.
<?php
declare(strict_types=1);
namespace Tests\Feature\Reservations;
use App\Booking\GuestId;
use App\Reservations\ReservationId;
use App\Reservations\ReservationStatus;
use App\Reservations\ReservationSummaryQuery;
use App\Reservations\ReservationSummaryQueryHandler;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
final class ReservationSummaryQueryHandlerTest extends TestCase
{
use RefreshDatabase;
public function test_it_reads_the_summary_in_one_query(): void
{
$reservationId = ReservationId::next();
$guestId = GuestId::next();
$database = $this->app->make(ConnectionInterface::class);
$database->table('guests')->insert(['id' => $guestId->value, 'full_name' => 'Ana Petrovska']);
$database->table('rooms')->insert(['id' => 14, 'number' => '214']);
$database->table('reservations')->insert([
'id' => $reservationId->value,
'guest_id' => $guestId->value,
'room_id' => 14,
'check_in' => '2026-05-06',
'check_out' => '2026-05-09',
'status' => ReservationStatus::Confirmed->value,
'adults' => 2,
'children' => 0,
'price_cents' => 42000,
'currency' => 'USD',
]);
$handler = $this->app->make(ReservationSummaryQueryHandler::class);
$summary = $handler->handle(new ReservationSummaryQuery($reservationId));
$this->assertSame('Ana Petrovska', $summary->guestName);
$this->assertSame('214', $summary->roomNumber);
$this->assertSame(ReservationStatus::Confirmed, $summary->status);
$this->assertSame(42000, $summary->totalPrice->amountInCents);
}
}Why reads skip the repository and the rich model
The repository and Reservation exist to protect rules, and rules apply when something changes. Reservation::cancel() refuses a reservation that isn't confirmed. checkIn() checks the status. A page that only displays a reservation can't break any of those rules, so loading the object that guards them buys nothing.
Skipping them also removes a pull in the wrong direction. Once a screen needs the guest's name, the temptation is to add a guestName field to Reservation so the repository can return it. Now the write model carries data that no rule needs, only because one page wanted it. The read DTO carries what the page needs and the entity carries what the rules need. Neither is shaped by the other.
The handler returns a ReservationSummary and not a Reservation for the same reason. An entity handed to a template can have its methods called by the template, and a query that returns it has quietly become a way to change state.
A query object or plain arguments
ReservationSummaryQuery holds one id. The Specification pattern lesson's SearchRoomsHandler::handle(DateRange $stayDates, GuestCount $guestCount) takes its inputs as plain arguments and has no query class at all. Both shapes are correct, and they suit different situations.
Plain arguments fit a query with one caller and a few inputs. The signature documents itself, and there is one fewer class. A query object fits once the query is handed around as a unit: queued to run later, logged with its inputs, used as a cache key, or called from several places that all need to build the same input.
For ReservationSummaryQuery, a single id, plain arguments would do (handle(ReservationId $reservationId)). The query object appears here so the read side mirrors the write side and the name carries over to the next lesson. If your page is the only caller, drop the object. A query bus, the query-side twin of the command bus, can sit between caller and handler too; you don't need one, and a later lesson covers it.
Pitfalls
Query handlers that write. A handler named GetReservationSummaryQueryHandler that also stamps last_viewed_at is a command wearing a query's name. Callers will assume they can call it twice, and command-query separation explains why a retry or a double click would then change data. If viewing has to be recorded, record it in a separate command.
Calling the repository from the query handler. A handler that calls $this->reservations->withId() and copies fields out of the entity into the DTO has the cost of both approaches: the full load and the mapping. It also can't include the guest name, since the entity doesn't hold it. If you find a query handler importing the Reservations repository, the read should go to the database instead.
Returning Eloquent models. A handler that ends in ->first() on a ReservationModel and returns it hands the template an object with save() and lazy-loaded relations. Each relation the template touches adds a query you can't see in the handler. Map to a DTO inside the handler, so the query count is what the handler's code shows.
One handler per screen growing into an unplanned reporting layer. The first handler serves one page. Then the admin list wants the same fields plus filters, the export wants every row, and the handler grows optional arguments for each. Split by what the screen needs, not by the table. A list that needs 50 rows with five columns is a different query from a detail page, even though both read reservations.
The one thing to remember
A read gets its own handler that queries the data directly and returns a read DTO shaped for the screen, never an entity. The rich model guards rules on writes, and a read has no rules to guard.
Related Links
- Laravel 13 Database: Query BuilderThe Laravel docs for the query builder, including joins and first(), used by the handler in this lesson.
- Read with the author (Matthias Noback)A small Symfony app that keeps its screens on separate read models returning DTOs.
- Command Query Separation (Martin Fowler)Fowler's definition of a query as a method that returns a result and does not change the observable state of the system.