Lesson 15 of 22 · Request Handling and API Design
Laravel Mass Assignment Straight From the Request
Reservations live in their own module, and requesting one is a command and a handler: the controller builds a RequestReservationCommand, hands it to the bus, and RequestReservationCommandHandler does the work. The command introduced a habit: it carries an array, and the array is whatever the Form Request validated.
<?php
declare(strict_types=1);
namespace App\Reservations\RequestReservation;
final readonly class RequestReservationCommand
{
/**
* @param array<string, mixed> $attributes
*/
public function __construct(
public int $guestId,
public array $attributes,
) {
}
}<?php
declare(strict_types=1);
namespace App\Reservations\RequestReservation;
use App\Reservations\ReservationRequest;
use Illuminate\Contracts\Bus\Dispatcher;
use Illuminate\Http\JsonResponse;
final readonly class RequestReservationController
{
public function __construct(
private Dispatcher $bus,
) {
}
public function __invoke(ReservationRequest $request): JsonResponse
{
$reservation = $this->bus->dispatch(new RequestReservationCommand(
guestId: (int) $request->user()->guest_id,
attributes: $request->validated(),
));
return (new RequestReservationResource($reservation))->response()->setStatusCode(201);
}
}<?php
declare(strict_types=1);
namespace App\Reservations\RequestReservation;
use App\Guests\Guest\Guest;
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
{
$guest = Guest::query()->findOrFail($command->guestId);
$room = Room::query()->with('roomType')->findOrFail($command->attributes['room_id']);
$checkIn = CarbonImmutable::parse($command->attributes['check_in']);
$checkOut = CarbonImmutable::parse($command->attributes['check_out']);
$reservation = Reservation::query()->create([
'guest_id' => $guest->id,
'status' => ReservationStatus::CONFIRMED,
'confirmed_at' => CarbonImmutable::now(),
'confirmation_code' => Str::upper(Str::random(8)),
'total_cents' => $this->pricing->totalCents($room->roomType, $checkIn, $checkOut),
...$command->attributes,
]);
$this->events->dispatch(new ReservationConfirmed($reservation->id, $guest->id));
return $reservation;
}
}The spread comes last, so any key in the validated array wins over the values the handler computed above it.
Read the create() call again. It writes guest_id, status, confirmed_at, confirmation_code, and total_cents by name, and everything else by whatever keys happen to be in $command->attributes. Nothing in this file says which columns a reservation request is allowed to write. That decision lives in a different class, ReservationRequest, and it lives there by accident.
The request shape is the write shape
ReservationRequest is shared. The web form uses it to request a reservation, and the PATCH endpoint from the old resource controller uses it to change one. The PATCH needs a status field, because that is how it cancels and checks in. So the request has a status rule:
<?php
declare(strict_types=1);
namespace App\Reservations;
use Illuminate\Foundation\Http\FormRequest;
final class ReservationRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
/**
* @return array<string, list<string>>
*/
public function rules(): array
{
$creating = $this->isMethod('post');
return [
'room_id' => [$creating ? 'required' : 'sometimes', 'integer', 'exists:rooms,id'],
'check_in' => [$creating ? 'required' : 'sometimes', 'date_format:Y-m-d', 'after_or_equal:today'],
'check_out' => [$creating ? 'required' : 'sometimes', 'date_format:Y-m-d', 'after:check_in'],
'adults' => [$creating ? 'required' : 'sometimes', 'integer', 'min:1'],
'children' => ['sometimes', 'integer', 'min:0'],
'status' => ['sometimes', 'in:cancelled,checked_in'],
];
}
}The web form never sends status, so nobody noticed what the rule does to the POST endpoint. Send this from a terminal:
POST /api/reservations
{"room_id": 12, "check_in": "2027-11-02", "check_out": "2027-11-05", "adults": 2, "status": "checked_in"}validated() returns every key that has a rule and passed, so it returns status too. The spread in the handler puts status into the create() array after the handler's own 'status' => ReservationStatus::CONFIRMED, so the client's value wins. The reservation lands in the database already checked in, for a guest who has not arrived, and the confirmation email goes out. The request class was the only thing standing between the client and the status column, and the request class was never meant to be that.
The module move also deleted $fillable from the model and called Model::unguard() in AppServiceProvider. That did not cause this bug, and putting $fillable back would not fix it. status is a real column that staff legitimately set, so it would be in the $fillable list. $fillable describes what the model can ever accept. It cannot describe what this one endpoint should accept. With unguard() in place, create() writes every key it is given. The only guard left is the code that names the keys.
Name every column you write
The command stops carrying an array. It carries the fields a reservation request has, one property each:
<?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 controller reads each field from the request by name and by type. integer() casts, string() returns a Stringable and toString() unwraps it:
<?php
declare(strict_types=1);
namespace App\Reservations\RequestReservation;
use App\Reservations\ReservationRequest;
use Illuminate\Contracts\Bus\Dispatcher;
use Illuminate\Http\JsonResponse;
final readonly class RequestReservationController
{
public function __construct(
private Dispatcher $bus,
) {
}
public function __invoke(ReservationRequest $request): JsonResponse
{
$reservation = $this->bus->dispatch(new RequestReservationCommand(
guestId: (int) $request->user()->guest_id,
roomId: $request->integer('room_id'),
checkIn: $request->string('check_in')->toString(),
checkOut: $request->string('check_out')->toString(),
adults: $request->integer('adults'),
children: $request->integer('children'),
));
return (new RequestReservationResource($reservation))
->response()
->setStatusCode(201);
}
}The handler writes each column by name, and the spread is gone:
<?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;
}
}Send the same POST with "status": "checked_in" again. Validation still passes, because the rule is still there and the PATCH still needs it. The controller never reads status, so the command never carries it, so the handler never writes it. The reservation is created confirmed, which is the only status a new request can have. To change that, someone has to add a property to the command and a line to the handler, and both of those show up in a diff with the word status in it.
The guest lookup is gone as well. The controller reads guest_id off the authenticated user, and the import creates its guest before it builds the command. The trade-off is that an unknown guest id used to return a 404 from findOrFail() and now fails on the foreign key when the insert runs.
The list of columns a reservation request writes is now the create() array in one file. You can read it without opening the request class or the migration. When a column is added to the table for a different use case, this handler does not start writing it until someone types its name here. The command's constructor is the contract for every caller, so a caller that leaves out adults fails when PHP refuses to construct the command.
What the second caller gets
The import controller passed an attributes array, so it changes to the named fields:
<?php
declare(strict_types=1);
namespace App\Reservations\ImportChannelReservations;
use App\Guests\Guest\Guest;
use App\Reservations\RequestReservation\RequestReservationCommand;
use Illuminate\Contracts\Bus\Dispatcher;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
final readonly class ImportChannelReservationsController
{
public function __construct(
private Dispatcher $bus,
) {
}
public function __invoke(Request $request): JsonResponse
{
$rows = $request->input('reservations', []);
foreach ($rows as $row) {
$guest = Guest::query()->firstOrCreate(
['email' => $row['guest']['email']],
['name' => $row['guest']['name'], 'phone' => $row['guest']['phone'] ?? null],
);
$this->bus->dispatch(new RequestReservationCommand(
guestId: $guest->id,
roomId: (int) $row['room_id'],
checkIn: (string) $row['arrival'],
checkOut: (string) $row['departure'],
adults: (int) $row['adults'],
children: (int) $row['children'],
));
}
return new JsonResponse(['imported' => count($rows)], 200);
}
}If the form's request class grows a field the import does not know about, nothing changes for the import, because the handler only writes what the command carries.
The one thing to remember
validated() answers "which input was well-formed", and that is a different question from "which columns this use case writes". Hand the model a spread array and the second answer is whatever the request class says today. Name every column in the handler and the write shape lives in one place you can read.