Skip to content

Lesson 27 of 45 · Commands and Queries

CQRS: Separate Models for Reads and Writes

Intermediate•
lesson•
November 3, 2026•
~10 min read

Two handlers, one table, no shared class

The CheckOutGuestCommandHandler loads a Reservation through the Reservations repository, tells it to check out, and saves it. The ReservationSummaryQueryHandler joins reservations to guests and rooms and returns a ReservationSummary. Both touch the reservations table. They share no class: the write side never sees a ReservationSummary, and the read side never loads a Reservation.

That split is CQRS, Command and Query Responsibility Segregation, and you are already doing its first level.

Where the name comes from

Bertrand Meyer's command-query separation applies to methods: each method either changes state or returns a value. CQRS applies the same idea to whole objects. Greg Young's "CQRS Documents" puts it this way: "The fundamental difference is that in CQRS objects are split into two objects, one containing the Commands one containing the Queries." The same document says it "was originally considered just to be an extension of this concept" and was later "deemed to be a different pattern."

Martin Fowler's page on CQRS, dated 14 July 2011, says it is "a pattern that I first heard described by Greg Young."

The two sides in this course

Put the classes you have built side by side.

Write side

Read side

Entry point

CheckOutGuestCommand

ReservationSummaryQuery

Handler

CheckOutGuestCommandHandler

ReservationSummaryQueryHandler

Loads

Reservation through Reservations

rows through a query builder

Returns

nothing

ReservationSummary

Holds the rules

Reservation

nothing

May change state

yes

no

The write side is shaped by the rules and the read side by the screens. Changing a screen touches the read side only. Changing a cancellation rule touches the write side only.

Giving the read side its own interface

The ReservationSummaryQueryHandler holds the query itself. Once a second page needs the same summary, say an admin page for the same reservation, you would copy the query or call the first handler from the second. Extract the query behind an interface instead, next to the Reservations repository and in the same domain terms:

PHP
<?php declare(strict_types=1); namespace App\Reservations; interface ReservationSummaries { /** @throws Exceptions\ReservationNotFound */ public function forReservation(ReservationId $reservationId): ReservationSummary; }

The implementation is the handler's query, moved. It lives in infrastructure like EloquentReservations does, so the interface stays free of any framework class.

PHP
<?php declare(strict_types=1); namespace App\Reservations\Infrastructure; use App\Billing\Currency; use App\Billing\Money; use App\Reservations\Exceptions\ReservationNotFound; use App\Reservations\ReservationId; use App\Reservations\ReservationStatus; use App\Reservations\ReservationSummaries; use App\Reservations\ReservationSummary; use DateTimeImmutable; use Illuminate\Database\ConnectionInterface; final readonly class QueryBuilderReservationSummaries implements ReservationSummaries { public function __construct(private ConnectionInterface $connection) {} public function forReservation(ReservationId $reservationId): ReservationSummary { $row = $this->connection->table('reservations') ->join('guests', 'guests.id', '=', 'reservations.guest_id') ->join('rooms', 'rooms.id', '=', 'reservations.room_id') ->where('reservations.id', $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($reservationId); } return new ReservationSummary( reservationId: $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 binding goes next to the repository's, in the ReservationsServiceProvider from the dependency injection lesson:

PHP
<?php declare(strict_types=1); namespace App\Providers; use App\Framework\Events\EventDispatcher; use App\Framework\Events\LaravelEventDispatcher; use App\Reservations\Infrastructure\EloquentReservations; use App\Reservations\Infrastructure\QueryBuilderReservationSummaries; use App\Reservations\Reservations; use App\Reservations\ReservationSummaries; use App\Support\SystemClock; use Illuminate\Support\ServiceProvider; use Psr\Clock\ClockInterface; final class ReservationsServiceProvider extends ServiceProvider { public function register(): void { $this->app->bind(Reservations::class, EloquentReservations::class); $this->app->bind(ReservationSummaries::class, QueryBuilderReservationSummaries::class); $this->app->bind(EventDispatcher::class, LaravelEventDispatcher::class); $this->app->bind(ClockInterface::class, SystemClock::class); } }

ReservationSummaryQueryHandler shrinks to one line:

PHP
<?php declare(strict_types=1); namespace App\Reservations; final readonly class ReservationSummaryQueryHandler { public function __construct(private ReservationSummaries $summaries) {} public function handle(ReservationSummaryQuery $query): ReservationSummary { return $this->summaries->forReservation($query->reservationId); } }

When nothing wraps it, a handler like that adds nothing, so the admin page can depend on ReservationSummaries directly:

PHP
<?php declare(strict_types=1); namespace App\Http\Controllers\Admin; use App\Reservations\ReservationId; use App\Reservations\ReservationSummaries; use Illuminate\Contracts\View\View; final class ShowReservationController { public function __invoke(string $reservationId, ReservationSummaries $summaries): View { return view('admin.reservations.show', [ 'summary' => $summaries->forReservation(new ReservationId($reservationId)), ]); } }

Once a query bus sits in front of the handlers, keep the handler, since the bus routes each query to one. That is the shape Noback uses with Sessions.

A test gets the same benefit as the write side's InMemoryReservations: a fake that returns canned DTOs and needs no database.

PHP
<?php declare(strict_types=1); namespace App\Testing; use App\Reservations\Exceptions\ReservationNotFound; use App\Reservations\ReservationId; use App\Reservations\ReservationSummaries; use App\Reservations\ReservationSummary; final class InMemoryReservationSummaries implements ReservationSummaries { /** @var array<string, ReservationSummary> */ private array $summaries = []; public function add(ReservationSummary $summary): void { $this->summaries[$summary->reservationId->value] = $summary; } public function forReservation(ReservationId $reservationId): ReservationSummary { return $this->summaries[$reservationId->value] ?? throw new ReservationNotFound($reservationId); } }

The admin page test puts the fake in the container and checks that the page gets the summary. No table is seeded, and the test has no RefreshDatabase. The route is Route::get('/admin/reservations/{reservationId}', ShowReservationController::class), and the admin.reservations.show template isn't shown.

PHP
<?php declare(strict_types=1); namespace Tests\Feature\Admin; use App\Billing\Currency; use App\Billing\Money; use App\Reservations\ReservationId; use App\Reservations\ReservationStatus; use App\Reservations\ReservationSummaries; use App\Reservations\ReservationSummary; use App\Testing\InMemoryReservationSummaries; use DateTimeImmutable; use Tests\TestCase; final class ShowReservationControllerTest extends TestCase { public function test_it_shows_the_summary_without_a_database(): void { $summary = new ReservationSummary( reservationId: ReservationId::next(), guestName: 'Ana Petrovska', roomNumber: '214', checkIn: new DateTimeImmutable('2026-05-06'), checkOut: new DateTimeImmutable('2026-05-09'), status: ReservationStatus::Confirmed, totalPrice: Money::fromCents(42000, Currency::usd()), ); $summaries = new InMemoryReservationSummaries(); $summaries->add($summary); $this->app->instance(ReservationSummaries::class, $summaries); $this->get('/admin/reservations/' . $summary->reservationId->value) ->assertOk() ->assertViewHas('summary', $summary); } }

Keep the two sides from reaching into each other. The read side imports ReservationSummary and never Reservation. The write side imports Reservation and Reservations and never ReservationSummary. A single use line that crosses the split, such as a command handler that calls ReservationSummaries to decide what to do, is the first sign the split is eroding. When a handler needs data to decide, it loads the entity, because the entity is the one object that holds the rules and the current state together.

Both sides still read and write the same tables. This is the whole of the first level: separate classes, one database.

The next step, and what it costs

A second level exists. Instead of joining reservations, guests and rooms on every page view, you keep a reservation_summaries table with one flat row per reservation, holding exactly the columns the page shows. Listeners on the reservation's events insert or update the row: ReservationConfirmed from the Domain Events lesson adds it, and the events for cancelling and checking out change its status. The read side then runs a single-table lookup and no join.

Here is a sketch of that step, so you can see its size. The table has reservation_id as its primary key and one column per value the page shows: guest_name, room_number, check_in, check_out, status, and price_cents with currency for the total price. A queued listener on ReservationConfirmed writes the row:

PHP
<?php declare(strict_types=1); namespace App\Reservations\Listeners; use App\Reservations\Events\ReservationConfirmed; use App\Reservations\ReservationStatus; use Illuminate\Contracts\Queue\ShouldQueueAfterCommit; use Illuminate\Database\ConnectionInterface; final readonly class AddReservationSummaryRow implements ShouldQueueAfterCommit { public function __construct(private ConnectionInterface $connection) {} public function handle(ReservationConfirmed $event): void { $guestName = $this->connection->table('guests')->where('id', $event->guestId->value)->value('full_name'); $roomNumber = $this->connection->table('rooms')->where('id', $event->roomId->value)->value('number'); $this->connection->table('reservation_summaries')->upsert( [ 'reservation_id' => $event->reservationId->value, 'guest_name' => $guestName, 'room_number' => $roomNumber, 'check_in' => $event->stayDates->checkIn->format('Y-m-d'), 'check_out' => $event->stayDates->checkOut->format('Y-m-d'), 'status' => ReservationStatus::Confirmed->value, 'price_cents' => $event->totalPrice->amountInCents, 'currency' => $event->totalPrice->currency->isoCode, ], uniqueBy: ['reservation_id'], ); } }

upsert() inserts the row or overwrites it in one statement, so the repeat delivery the Domain Events lesson warned about does no harm. The listener copies the guest's name and the room number at confirm time, so a later rename needs a listener of its own. The read side gets a second implementation of the same interface:

PHP
<?php declare(strict_types=1); namespace App\Reservations\Infrastructure; use App\Billing\Currency; use App\Billing\Money; use App\Reservations\Exceptions\ReservationNotFound; use App\Reservations\ReservationId; use App\Reservations\ReservationStatus; use App\Reservations\ReservationSummaries; use App\Reservations\ReservationSummary; use DateTimeImmutable; use Illuminate\Database\ConnectionInterface; final readonly class TableReservationSummaries implements ReservationSummaries { public function __construct(private ConnectionInterface $connection) {} public function forReservation(ReservationId $reservationId): ReservationSummary { $row = $this->connection->table('reservation_summaries') ->where('reservation_id', $reservationId->value) ->first(); if ($row === null) { throw new ReservationNotFound($reservationId); } return new ReservationSummary( reservationId: $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 switch is one line in the provider, ReservationSummaries::class bound to TableReservationSummaries::class, plus the listener registered in the ReservationEventServiceProvider. The admin page, the handler and the fake don't change, which is what the interface bought. This course stays on the first level, so later lessons don't carry these two classes.

The cost is a lag. The listener runs after the write, and when it is queued (with ShouldQueueAfterCommit) it runs on a worker some time later. A guest who confirms a reservation and reloads the page can see the old state until the listener finishes. This is called eventual consistency: the read table agrees with the write tables, but not at the same instant. You also take on a second place that can be wrong, and a job to rebuild the table when a listener fails or a column is added.

Fowler is blunt about this: "you should be very cautious about using CQRS," and "CQRS is a significant mental leap for all concerned, so shouldn't be tackled unless the benefit is worth the jump." A later course in this series builds the read table.

CQRS is often paired with event sourcing, which stores events instead of current state. You can do either without the other, and a later course in this series covers event sourcing.

When it earns its place

The first level earns its place as soon as you have rich entities and screens that read across tables. It costs one interface and one DTO per screen, and it stops the write model from growing fields for display.

A separate read table earns its place when one screen needs a shape the write tables can't serve cheaply. A dashboard that counts occupied rooms per night for the next 90 days is an example: a join and a group on every page view is slow, and the answer can be a little stale without harm. Measure the query first. If an index fixes it, you don't need a table.

The first level isn't worth it for a settings screen, or for a model with one reader and one writer where the page shows what the entity holds. Reading the entity through its repository is simpler there.

Pitfalls

"CQRS means two databases." The split is between classes. The summary query reads the same tables the repository writes. Two databases is one possible way to host a separate read table, and it adds replication lag on top of the lag above.

Command handlers that return read models. A handler that saves the reservation and then returns a ReservationSummary so the controller can render it has blurred the two sides again, and it breaks the rule that a command returns nothing. The controller generates the id, sends the command, and then calls the read side with that id. This is the RequestReservationController from the command-query separation lesson as a JSON endpoint:

PHP
<?php declare(strict_types=1); namespace App\Http\Controllers\Api; use App\Http\Requests\RequestReservationRequest; use App\Reservations\RequestReservationCommand; use App\Reservations\RequestReservationCommandHandler; use App\Reservations\RequestReservationData; use App\Reservations\ReservationId; use App\Reservations\ReservationSummaries; use Illuminate\Http\JsonResponse; final class RequestReservationController { public function __invoke( RequestReservationRequest $request, RequestReservationCommandHandler $handler, ReservationSummaries $summaries, ): JsonResponse { $data = RequestReservationData::fromRequest($request); $reservationId = ReservationId::next(); $handler->handle(new RequestReservationCommand( reservationId: $reservationId, guestId: $data->guestId, roomId: $data->roomId, stayDates: $data->stayDates, guestCount: $data->guestCount, ratePlanCode: $data->ratePlanCode, )); $summary = $summaries->forReservation($reservationId); return new JsonResponse([ 'id' => $reservationId->value, 'room' => $summary->roomNumber, 'status' => $summary->status->value, 'total_cents' => $summary->totalPrice->amountInCents, ], 201); } }

The two sides meet only in the controller. The handler never sees a ReservationSummary, and ReservationSummaries never sees a command. On the first level this works because the read follows the write in the same database. With the read table above, this read fails: a requested reservation has no row until it is confirmed, and even then the row waits for a worker to run the listener.

Splitting a model with one reader and one writer. If the only read of an entity is the handler that also changes it, and the page shows exactly what the entity holds, a read class duplicates the entity's fields for no gain. Split when reads and writes want different shapes, not before.

The one thing to remember

Rich entities behind command handlers and read DTOs behind query handlers is CQRS at its first level, and an application can stop there. Add a separate read table only when a screen needs a shape the write tables can't serve cheaply, and expect stale reads when you do.

Course Content