Skip to content

Lesson 19 of 22 · Primitives and Value Objects

Laravel DTOs Instead of Arrays for Everything

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

The previous lessons left the reservations module with an honest API. RequestReservationCommand names its six fields, the handler writes each column by name, and the multi-purpose PATCH is gone. One shape survived every refactor so far: the associative array. The channel import, the reason this course exists, reads the channel manager's JSON row by key. And the handler hands the whole Reservation model back to the controller, which is the same problem in a different coat: a bag of whatever happened to be loaded. This lesson replaces both with data transfer objects, DTOs for short.

The import changes shape in this lesson too. The push endpoint is gone, because the channel manager pushed whenever it liked and the property wants the import on its own schedule. ImportChannelReservationsController and its route are deleted: remove its use line and its Route::post('/reservations/import', ...) line from reservations-routes.php. In their place is a queued job that pulls the rows itself, and this is its first draft, written straight against the channel manager's JSON. That JSON changed too: it identifies rooms by number instead of id, and it nests the guest counts in an occupancy object.

The array coming in from the channel

The array here is somebody else's shape:

PHP
<?php declare(strict_types=1); namespace App\Reservations\ImportChannelReservations; use App\Guests\Guest\Guest; use App\Reservations\RequestReservation\RequestReservationCommand; use App\Rooms\Room\Room; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Bus\Dispatcher; use Illuminate\Contracts\Queue\ShouldQueue; use Psr\Log\LoggerInterface; final class ImportChannelReservationsJob implements ShouldQueue { use Queueable; public function handle(ChannelFeed $feed, Dispatcher $bus, LoggerInterface $logger): void { foreach ($feed->rows() as $row) { $bus->dispatch(new RequestReservationCommand( guestId: $this->resolveGuestId($row), roomId: $this->resolveRoomId($row), checkIn: $row['arrival'], checkOut: $row['departure'], adults: $row['occupancy']['adults'], children: $row['occupancy']['children'] ?? 0, )); $logger->info('Channel reservation imported', ['reference' => $row['reference']]); } } /** * @param array<string, mixed> $row */ private function resolveGuestId(array $row): int { return Guest::query()->firstOrCreate( ['email' => $row['guest']['email']], ['name' => $row['guest']['name'], 'phone' => $row['guest']['phone'] ?? null], )->id; } /** * @param array<string, mixed> $row */ private function resolveRoomId(array $row): int { return Room::query()->where('number', $row['room'])->firstOrFail()->id; } }

ChannelFeed is the interface in front of the channel manager. In this draft it hands back decoded JSON:

PHP
<?php declare(strict_types=1); namespace App\Reservations\ImportChannelReservations; interface ChannelFeed { /** * @return iterable<int, array<string, mixed>> */ public function rows(): iterable; }

Count the places that know the channel's key names: handle() knows arrival, departure, occupancy, and reference. resolveGuestId() knows guest.email, guest.name, and guest.phone. resolveRoomId() knows room. When the channel manager renames occupancy to guests in their next API version, you find the reads with grep and hope none of them were built from a variable. Miss one and PHP raises an undefined-array-key warning on the first row, which Laravel's error handler turns into an ErrorException, at runtime, in the worker. The array<string, mixed> annotation is honest about what the type system knows, which is nothing.

Stop the array at the edge

An array is the right shape for exactly one moment: the instant after json_decode(). From there, convert it into an object whose constructor names every field with a type. That object is a data transfer object, a DTO: a class whose only job is to carry named, typed values from one place to another. It has no behaviour beyond construction. RequestReservationCommand has been one since it was introduced; the name just did not come up.

The channel row becomes a DTO with one static constructor, and that constructor is the only method in the codebase that knows the channel's key names. It is also where the channel's offset timestamps, such as 2026-10-03T00:00:00+02:00, become plain Y-m-d dates:

PHP
<?php declare(strict_types=1); namespace App\Reservations\ImportChannelReservations; use Carbon\CarbonImmutable; final readonly class ChannelReservationRow { public function __construct( public string $reference, public string $guestName, public string $guestEmail, public ?string $guestPhone, public string $roomNumber, public string $arrival, public string $departure, public int $adults, public int $children, ) {} /** * @param array{ * reference: string, * guest: array{name: string, email: string, phone?: string}, * room: string, * arrival: string, * departure: string, * occupancy: array{adults: int, children?: int} * } $row */ public static function fromPayload(array $row): self { return new self( reference: $row['reference'], guestName: $row['guest']['name'], guestEmail: $row['guest']['email'], guestPhone: $row['guest']['phone'] ?? null, roomNumber: $row['room'], arrival: CarbonImmutable::parse($row['arrival'])->toDateString(), departure: CarbonImmutable::parse($row['departure'])->toDateString(), adults: $row['occupancy']['adults'], children: $row['occupancy']['children'] ?? 0, ); } }

The array-shape comment on fromPayload() is for PHPStan and for the reader. PHP does not enforce it, and that is acceptable here because the shape is read in one method. Everywhere else the row is ChannelReservationRow, and PHP enforces the type of every property on it.

ChannelFeed now returns rows:

PHP
<?php declare(strict_types=1); namespace App\Reservations\ImportChannelReservations; interface ChannelFeed { /** * @return iterable<int, ChannelReservationRow> */ public function rows(): iterable; }

The HTTP implementation decodes the channel manager's response and maps each element through ChannelReservationRow::fromPayload(). The job reads properties:

PHP
<?php declare(strict_types=1); namespace App\Reservations\ImportChannelReservations; use App\Guests\Guest\Guest; use App\Reservations\RequestReservation\RequestReservationCommand; use App\Rooms\Room\Room; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Bus\Dispatcher; use Illuminate\Contracts\Queue\ShouldQueue; use Psr\Log\LoggerInterface; final class ImportChannelReservationsJob implements ShouldQueue { use Queueable; public function handle(ChannelFeed $feed, Dispatcher $bus, LoggerInterface $logger): void { foreach ($feed->rows() as $row) { $guest = Guest::query()->firstOrCreate( ['email' => $row->guestEmail], ['name' => $row->guestName, 'phone' => $row->guestPhone], ); $room = Room::query()->where('number', $row->roomNumber)->firstOrFail(); $bus->dispatch(new RequestReservationCommand( guestId: $guest->id, roomId: $room->id, checkIn: $row->arrival, checkOut: $row->departure, adults: $row->adults, children: $row->children, )); $logger->info('Channel reservation imported', ['reference' => $row->reference]); } } }

The two private methods are gone because they existed to hide array reads. When the channel renames occupancy, one line in fromPayload() changes, and a typo in $row->arival is an ErrorException at the line that is wrong, and PHPStan flags it before that.

The model coming out of the handler

The same move applies on the way out. Here is the handler as it stands now, and the resource that reads its return value:

PHP
<?php declare(strict_types=1); namespace App\Reservations\RequestReservation; use App\Pricing\NightlyRatePricing; use App\Reservations\Reservation\Reservation; use App\Reservations\Reservation\ReservationStatus; use App\Rooms\Room\Room; use Carbon\CarbonImmutable; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Support\Str; final readonly class RequestReservationCommandHandler { public function __construct( private NightlyRatePricing $pricing, private Dispatcher $events, ) { } public function handle(RequestReservationCommand $command): Reservation { $room = Room::query() ->with('roomType') ->findOrFail($command->roomId); $checkIn = CarbonImmutable::parse($command->checkIn); $checkOut = CarbonImmutable::parse($command->checkOut); $reservation = Reservation::query()->create([ 'guest_id' => $command->guestId, 'room_id' => $room->id, 'check_in' => $checkIn, 'check_out' => $checkOut, 'adults' => $command->adults, 'children' => $command->children, 'status' => ReservationStatus::CONFIRMED, 'confirmed_at' => CarbonImmutable::now(), 'total_cents' => $this->pricing->totalCents($room->roomType, $checkIn, $checkOut), 'confirmation_code' => Str::upper(Str::random(8)), ]); $this->events->dispatch(new ReservationConfirmed( reservationId: $reservation->id, guestId: $reservation->guest_id, )); return $reservation; } }
PHP
<?php declare(strict_types=1); namespace App\Reservations\RequestReservation; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; final class RequestReservationResource extends JsonResource { /** * @return array<string, mixed> */ public function toArray(Request $request): array { return [ 'id' => $this->resource->id, 'total_cents' => $this->resource->total_cents, 'confirmation_code' => $this->resource->confirmation_code, ]; } }

The signature says Reservation, which promises every column and every relation, and delivers whichever of them this handler happened to load. The resource reads three attributes today. The day it reads $this->resource->guest->name, it passes a feature test, because a model that came out of create() is allowed to lazy load, and from then on it depends on the handler never changing what it loads. A return value that is a model is a bag with a class name on it.

The handler returns a DTO instead, carrying the three values the caller gets to know:

PHP
<?php declare(strict_types=1); namespace App\Reservations\RequestReservation; final readonly class RequestReservationResult { public function __construct( public int $reservationId, public int $totalCents, public string $confirmationCode, ) {} }

The handler becomes:

PHP
<?php declare(strict_types=1); namespace App\Reservations\RequestReservation; use App\Pricing\NightlyRatePricing; use App\Reservations\Reservation\Reservation; use App\Reservations\Reservation\ReservationStatus; use App\Rooms\Room\Room; use Carbon\CarbonImmutable; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Support\Str; final readonly class RequestReservationCommandHandler { public function __construct( private NightlyRatePricing $pricing, private Dispatcher $events, ) { } public function handle(RequestReservationCommand $command): RequestReservationResult { $room = Room::query() ->with('roomType') ->findOrFail($command->roomId); $checkIn = CarbonImmutable::parse($command->checkIn); $checkOut = CarbonImmutable::parse($command->checkOut); $reservation = Reservation::query()->create([ 'guest_id' => $command->guestId, 'room_id' => $room->id, 'check_in' => $checkIn, 'check_out' => $checkOut, 'adults' => $command->adults, 'children' => $command->children, 'status' => ReservationStatus::CONFIRMED, 'confirmed_at' => CarbonImmutable::now(), 'total_cents' => $this->pricing->totalCents($room->roomType, $checkIn, $checkOut), 'confirmation_code' => Str::upper(Str::random(8)), ]); $this->events->dispatch(new ReservationConfirmed( reservationId: $reservation->id, guestId: $reservation->guest_id, )); return new RequestReservationResult( reservationId: $reservation->id, totalCents: $reservation->total_cents, confirmationCode: $reservation->confirmation_code, ); } }

And the resource reads typed properties:

PHP
<?php declare(strict_types=1); namespace App\Reservations\RequestReservation; use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; /** * @property-read RequestReservationResult $resource */ final class RequestReservationResource extends JsonResource { /** * @return array<string, mixed> */ public function toArray(Request $request): array { return [ 'id' => $this->resource->reservationId, 'total_cents' => $this->resource->totalCents, 'confirmation_code' => $this->resource->confirmationCode, ]; } }

RequestReservationController only renames its variable: $result = $this->bus->dispatch(...), passed to new RequestReservationResource($result).

The handler's signature now says what it returns. Rename totalCents and the resource fails at the property read, in the resource, on the line that is stale. The import job that ships at the end of the course gets the same RequestReservationResult back from the same handler and logs $result->reservationId without guessing a key.

The array-of-rows in OccupancyReport stays an array. A report is a list of rows with the same fields, and OccupancyRow already types each row. The rule is about arrays that stand in for a named thing, not about lists.

The one thing to remember

An array crossing a method boundary is a shape nobody wrote down. Convert it to a typed object at the edge where it enters, in one method that owns the key names, and let every other signature say what it carries.

Course Content