Skip to content

Lesson 21 of 22 · Primitives and Value Objects

Laravel Value Objects Instead of Primitives

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

The command now reads like this:

PHP
<?php declare(strict_types=1); namespace App\Reservations\RequestReservation; final readonly class RequestReservationCommand { public function __construct( public int $guestId, public int $roomId, public string $checkIn, public string $checkOut, public int $adults, public int $children, ) { } }

The dates and the adult count carry rules that live somewhere else. Check-out must come after check-in: that rule is after:check_in in RequestReservationRequest. A reservation needs at least one adult: min:1 in the same Form Request. The total never reaches the command. It is an int of cents in the handler, the result, the resource, the ReservationConfirmationDetails object, and the pricing class, and the only thing stopping someone from passing dollars is the suffix on the name.

The Form Request guards the web form. The channel import has no Form Request. It builds the command from ChannelReservationRow, and if the channel sends a departure before the arrival, or an occupancy of zero adults, the handler parses both strings, hands two dates to the pricing class, and stores whatever the arithmetic produces. The rule "check-out after check-in" exists in the codebase and the second caller never meets it.

Put the rule in the type

A value object is a small class that wraps a value, checks it in the constructor, and carries the behaviour that belongs to it. Once the object exists, the value inside it is valid, so nothing downstream checks again. Three of them cover the command and the total.

DateRange holds the stay and refuses to exist with the dates the wrong way round:

PHP
<?php declare(strict_types=1); namespace App\Reservations\Reservation; use Carbon\CarbonImmutable; use InvalidArgumentException; final readonly class DateRange { public function __construct( public CarbonImmutable $checkIn, public CarbonImmutable $checkOut, ) { if ($checkOut->lessThanOrEqualTo($checkIn)) { throw new InvalidArgumentException(sprintf( 'Check-out %s must be after check-in %s.', $checkOut->toDateString(), $checkIn->toDateString(), )); } } public static function fromStrings(string $checkIn, string $checkOut): self { return new self( CarbonImmutable::createFromFormat('!Y-m-d', $checkIn), CarbonImmutable::createFromFormat('!Y-m-d', $checkOut), ); } public function nights(): int { return (int) $this->checkIn->diffInDays($this->checkOut); } public function isWeekOrLonger(): bool { return $this->nights() >= 7; } public function overlaps(self $other): bool { return $this->checkIn->lessThan($other->checkOut) && $other->checkIn->lessThan($this->checkOut); } }

nights() used to be a line in the pricing class. overlaps() did not exist anywhere, and an availability check, which this course does not build, will want it. Both belong on the range, because both are questions about the range.

GuestCount refuses zero adults and negative children:

PHP
<?php declare(strict_types=1); namespace App\Reservations\Reservation; use InvalidArgumentException; final readonly class GuestCount { public function __construct( public int $adults, public int $children, ) { if ($adults < 1) { throw new InvalidArgumentException('A reservation needs at least one adult.'); } if ($children < 0) { throw new InvalidArgumentException('Children cannot be negative.'); } } }

Money carries the amount in minor units (cents, for euros and dollars) and the currency together, refuses a negative amount, and owns the arithmetic that used to be scattered * $nights and * 0.9 expressions:

PHP
<?php declare(strict_types=1); namespace App\Shared; use InvalidArgumentException; final readonly class Money { public function __construct( public int $amount, public string $currency, ) { if ($amount < 0) { throw new InvalidArgumentException('Money cannot be negative.'); } if (preg_match('/^[A-Z]{3}$/', $currency) !== 1) { throw new InvalidArgumentException("Currency must be a three-letter ISO 4217 code, got {$currency}."); } } public function multiply(int $factor): self { return new self($this->amount * $factor, $this->currency); } public function withDiscountPercent(int $percent): self { return new self((int) round($this->amount * (100 - $percent) / 100), $this->currency); } }

Money lives in App\Shared because no module owns it, and any module that handles an amount will use it. DateRange and GuestCount live next to the Reservation model because they are reservation concepts. The pricing class imports DateRange from there.

The pricing rule, rewritten in the new words

The pricing class stops doing date arithmetic and percentage arithmetic. It says the rule:

PHP
<?php declare(strict_types=1); namespace App\Pricing; use App\Reservations\Reservation\DateRange; use App\Shared\Money; final readonly class NightlyRatePricing { public function total(Money $nightlyRate, DateRange $stayDates): Money { $total = $nightlyRate->multiply($stayDates->nights()); return $stayDates->isWeekOrLonger() ? $total->withDiscountPercent(10) : $total; } }

Compare that with the previous version. The $nights >= self::WEEKLY_DISCOUNT_MINIMUM_NIGHTS check became isWeekOrLonger(). The round() line became withDiscountPercent(10). The rounding lives in Money, once, and any future discount uses the same rounding without anyone remembering to cast. NightlyRatePricingTest changes with the signature: it builds a Money and a DateRange and asserts on total()->amount, with the same 75600 and 72000 expectations. ChangeReservationDatesCommandHandler builds a DateRange from its two dates and calls total($reservation->room->roomType->nightlyRate(), $stayDates), and so does the quote page. The handler then passes $stayDates->checkIn, $stayDates->checkOut and $total->amount to changeDates(), which still takes the same three arguments.

RoomType hands out its rate as Money (the room_types and reservations tables each get a three-letter currency column next to the cents column):

PHP
<?php declare(strict_types=1); namespace App\Rooms\RoomType; use App\Rooms\Room\Room; use App\Shared\Money; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\SoftDeletes; class RoomType extends Model { /** @use HasFactory<RoomTypeFactory> */ use HasFactory; use SoftDeletes; protected static function newFactory(): RoomTypeFactory { return new RoomTypeFactory(); } public function rooms(): HasMany { return $this->hasMany(Room::class); } public function nightlyRate(): Money { return new Money($this->nightly_rate_cents, $this->currency); } }

The command, the handler, and the callers

The command carries objects:

PHP
<?php declare(strict_types=1); namespace App\Reservations\RequestReservation; use App\Reservations\Reservation\DateRange; use App\Reservations\Reservation\GuestCount; final readonly class RequestReservationCommand { public function __construct( public int $guestId, public int $roomId, public DateRange $stayDates, public GuestCount $guestCount, ) { } }

The handler no longer parses strings or multiplies integers:

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); $total = $this->pricing->total($room->roomType->nightlyRate(), $command->stayDates); $reservation = Reservation::query()->create([ 'guest_id' => $command->guestId, 'room_id' => $room->id, 'check_in' => $command->stayDates->checkIn, 'check_out' => $command->stayDates->checkOut, 'adults' => $command->guestCount->adults, 'children' => $command->guestCount->children, 'status' => ReservationStatus::CONFIRMED, 'confirmed_at' => CarbonImmutable::now(), 'total_cents' => $total->amount, 'currency' => $total->currency, '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, total: $total, confirmationCode: $reservation->confirmation_code, ); } }

RequestReservationResult carries Money $total instead of int $totalCents:

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

The resource serialises total_cents and currency from it:

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->total->amount, 'currency' => $this->resource->total->currency, 'confirmation_code' => $this->resource->confirmationCode, ]; } }

ReservationConfirmationDetails swaps int $totalCents for Money $total, the listener builds it with new Money($reservation->total_cents, $reservation->currency), and the template reads $details->total->amount.

The web controller builds the objects at the boundary:

PHP
<?php declare(strict_types=1); namespace App\Reservations\RequestReservation; use App\Reservations\Reservation\DateRange; use App\Reservations\Reservation\GuestCount; use Illuminate\Contracts\Bus\Dispatcher; use Illuminate\Http\JsonResponse; final readonly class RequestReservationController { public function __construct( private Dispatcher $bus, ) { } public function __invoke(RequestReservationRequest $request): JsonResponse { $result = $this->bus->dispatch(new RequestReservationCommand( guestId: (int) $request->user()->guest_id, roomId: $request->integer('room_id'), stayDates: DateRange::fromStrings( $request->string('check_in')->toString(), $request->string('check_out')->toString(), ), guestCount: new GuestCount( adults: $request->integer('adults'), children: $request->integer('children'), ), )); return (new RequestReservationResource($result)) ->response() ->setStatusCode(201); } }

The import job builds them from ChannelReservationRow in the same way, with DateRange::fromStrings($row->arrival, $row->departure) and new GuestCount($row->adults, $row->children). A channel row with the dates reversed now throws InvalidArgumentException at the line that builds the range, with both dates in the message, before anything is priced or written.

What happens to the Form Request

Here is RequestReservationRequest as it stands now:

PHP
<?php declare(strict_types=1); namespace App\Reservations\RequestReservation; use Illuminate\Foundation\Http\FormRequest; final class RequestReservationRequest extends FormRequest { public function authorize(): bool { return $this->user()?->guest_id !== null; } /** * @return array<string, list<string>> */ public function rules(): array { return [ 'room_id' => ['required', 'integer', 'exists:rooms,id'], 'check_in' => ['required', 'date_format:Y-m-d', 'after_or_equal:today'], 'check_out' => ['required', 'date_format:Y-m-d', 'after:check_in'], 'adults' => ['required', 'integer', 'min:1'], 'children' => ['required', 'integer', 'min:0'], ]; } }

after:check_in, min:1 on adults, and min:0 on children now duplicate what the constructors enforce. Keep them anyway. The Form Request is the boundary that turns bad web input into a 422 with a field-level message. Without those rules a reversed date range would reach DateRange::fromStrings() in the controller and surface as a 500. The value object is the rule that cannot be skipped; the Form Request is the polite version of it for the one caller that has a form. after_or_equal:today stays a Form Request rule only, because the channel import legitimately imports past stays, and a rule that applies to one caller belongs at that caller's boundary.

What you no longer write is a second copy of the date rule in the import and a third in the admin form someone adds for walk-ins. DateRange is that rule.

The one thing to remember

A primitive with a rule attached is a class you have not written yet. Write it once with its rule in the constructor, and every caller, including the one that has no Form Request, gets the rule without asking.

Course Content