Lesson 17 of 22 · Request Handling and API Design
Laravel API Design: One Endpoint Doing Four Things
The old resource controller had an update() method, and it became ChangeReservationController without changing what it does. Here it reads the body with filled() and input() and compares the status against ReservationStatus cases instead of strings, with the same behaviour. It still answers PATCH /reservations/{id}, and what happens depends on which fields the body contains. Dates present: move the stay and reprice it. status set to cancelled: cancel. status set to checked_in: check the guest in. Cancellation got a route of its own, POST /reservations/{id}/cancel, but the status branch stayed, so a client can cancel either way and nothing says which is the real one. The controller is where the branching lives:
<?php
declare(strict_types=1);
namespace App\Reservations\ChangeReservation;
use App\Pricing\NightlyRatePricing;
use App\Reservations\Reservation\Reservation;
use App\Reservations\Reservation\ReservationStatus;
use App\Reservations\ReservationRequest;
use Carbon\CarbonImmutable;
use Illuminate\Http\JsonResponse;
final readonly class ChangeReservationController
{
public function __construct(
private NightlyRatePricing $pricing,
) {
}
public function __invoke(ReservationRequest $request, int $id): JsonResponse
{
$reservation = Reservation::query()
->with('room.roomType')
->findOrFail($id);
if ($request->filled('check_in') && $request->filled('check_out')) {
$checkIn = CarbonImmutable::parse($request->string('check_in')->toString());
$checkOut = CarbonImmutable::parse($request->string('check_out')->toString());
$reservation->check_in = $checkIn;
$reservation->check_out = $checkOut;
$reservation->total_cents = $this->pricing->totalCents($reservation->room->roomType, $checkIn, $checkOut);
}
if ($request->input('status') === ReservationStatus::CANCELLED->value) {
$reservation->status = ReservationStatus::CANCELLED;
}
if ($request->input('status') === ReservationStatus::CHECKED_IN->value) {
$reservation->status = ReservationStatus::CHECKED_IN;
}
$reservation->save();
return new JsonResponse(null, 204);
}
}That is three intents, and a fourth if you count "dates and cancel in the same body", which it also accepts.
Where it breaks
A guest can move their own stay and cancel it, and only the front desk checks a guest in. ReservationRequest::authorize() returns $this->user() !== null, which is the loosest rule that lets the guest's two actions through, and it lets the guest's third action through as well. A guest who reads the network tab can send {"status": "checked_in"} and check themselves in from the car park. To fix that inside this endpoint, authorize() has to look at the body, decide which intent it is looking at, and apply a different rule per branch. Send check_in and status together and whichever branch runs first decides for both.
Then the rules. Cancelling does not need dates. Checking in does not need dates. Moving a stay needs both dates and must not accept a status. One request class cannot say any of that, so every field is sometimes and any combination passes.
Then the transitions. Nothing stops a cancelled reservation from being checked in, or from having its dates moved afterwards. The controller sets whatever status the body named.
One endpoint per intent
Each intent becomes its own slice: a command that carries only what that intent needs, a handler, a request whose authorize() answers one question, a route whose URL says what it does. CancelReservation/ already holds the one-file controller split out of destroy(); it gains the command, handler, request, and event the check-in slice has, and the status branch that duplicated it goes.
app/Reservations/
ChangeReservationDates/
ChangeReservationDatesCommand.php
ChangeReservationDatesCommandHandler.php
ChangeReservationDatesController.php
CancelReservation/
CancelReservationCommand.php
CancelReservationCommandHandler.php
CancelReservationController.php
CancelReservationRequest.php
ReservationCancelled.php
CheckInGuest/
CheckInGuestCommand.php
CheckInGuestCommandHandler.php
CheckInGuestController.php
CheckInGuestRequest.php
GuestCheckedIn.phpThe transition rules move onto the model, where the status lives. Each method checks the transition and throws when it is not allowed:
<?php
declare(strict_types=1);
namespace App\Reservations\Reservation;
use App\Guests\Guest\Guest;
use App\Reservations\Payment\Payment;
use App\Rooms\Room\Room;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Reservation extends Model
{
/** @use HasFactory<ReservationFactory> */
use HasFactory;
protected function casts(): array
{
return [
'status' => ReservationStatus::class,
'check_in' => 'immutable_date',
'check_out' => 'immutable_date',
'confirmed_at' => 'immutable_datetime',
'cancelled_at' => 'immutable_datetime',
'checked_in_at' => 'immutable_datetime',
];
}
protected static function newFactory(): ReservationFactory
{
return new ReservationFactory();
}
public function guest(): BelongsTo
{
return $this->belongsTo(Guest::class);
}
public function room(): BelongsTo
{
return $this->belongsTo(Room::class);
}
public function payments(): HasMany
{
return $this->hasMany(Payment::class);
}
public function outstandingCents(): int
{
return $this->total_cents - (int) $this->paid_cents;
}
public function changeDates(CarbonImmutable $checkIn, CarbonImmutable $checkOut, int $totalCents): void
{
if ($this->status === ReservationStatus::CANCELLED || $this->status === ReservationStatus::CHECKED_OUT) {
throw new ReservationDatesCannotChange($this->id, $this->status);
}
$this->check_in = $checkIn;
$this->check_out = $checkOut;
$this->total_cents = $totalCents;
$this->save();
}
public function cancel(CarbonImmutable $now): void
{
if ($this->status === ReservationStatus::CANCELLED) {
throw new ReservationAlreadyCancelled($this->id);
}
if ($this->status === ReservationStatus::CHECKED_IN || $this->status === ReservationStatus::CHECKED_OUT) {
throw new ReservationCannotBeCancelled($this->id, $this->status);
}
$this->status = ReservationStatus::CANCELLED;
$this->cancelled_at = $now;
$this->save();
}
public function checkIn(CarbonImmutable $now): void
{
if ($this->status !== ReservationStatus::CONFIRMED) {
throw new ReservationCannotBeCheckedIn($this->id, $this->status);
}
$this->status = ReservationStatus::CHECKED_IN;
$this->checked_in_at = $now;
$this->save();
}
}A migration adds cancelled_at and checked_in_at. The four exceptions extend one base class for the module. The base class knows how to turn itself into a response, so no controller has to catch anything. Laravel calls render() on an exception that defines it:
<?php
declare(strict_types=1);
namespace App\Reservations;
use Illuminate\Http\JsonResponse;
use RuntimeException;
abstract class ReservationException extends RuntimeException
{
protected int $status = 422;
public function render(): JsonResponse
{
return new JsonResponse(['message' => $this->getMessage()], $this->status);
}
}<?php
declare(strict_types=1);
namespace App\Reservations\Reservation;
use App\Reservations\ReservationException;
final class ReservationAlreadyCancelled extends ReservationException
{
protected int $status = 409;
public function __construct(int $reservationId)
{
parent::__construct("Reservation {$reservationId} is already cancelled.");
}
}ReservationCannotBeCancelled and ReservationCannotBeCheckedIn take the id and the current status, build their message the same way, and answer 409 as well; ReservationDatesCannotChange does the same. They live next to the model in Reservation/.
The cancel slice has five files. CancelReservationCommand carries reservationId and nothing else. ReservationCancelled carries reservationId and guestId. CancelReservationController takes the request and an int $id, dispatches the command through the bus and returns 204. The handler and the request are the two worth reading:
<?php
declare(strict_types=1);
namespace App\Reservations\CancelReservation;
use App\Reservations\Reservation\Reservation;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\Events\Dispatcher;
final readonly class CancelReservationCommandHandler
{
public function __construct(
private Dispatcher $events,
) {
}
public function handle(CancelReservationCommand $command): void
{
$reservation = Reservation::query()->findOrFail($command->reservationId);
$reservation->cancel(CarbonImmutable::now());
$this->events->dispatch(new ReservationCancelled(
reservationId: $reservation->id,
guestId: $reservation->guest_id,
));
}
}The request has no rules, because the URL already says everything. It still exists, because authorize() is where the permission question is answered:
<?php
declare(strict_types=1);
namespace App\Reservations\CancelReservation;
use Illuminate\Foundation\Http\FormRequest;
final class CancelReservationRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
/**
* @return array<string, list<mixed>>
*/
public function rules(): array
{
return [];
}
}This only checks that someone is logged in. Whether the reservation belongs to that guest is an ownership check this lesson leaves out.
Check-in has the same shape: a controller that dispatches CheckInGuestCommand and returns 204, and a request with a different authorize(). The question that request asks is the one the shared request could not ask:
<?php
declare(strict_types=1);
namespace App\Reservations\CheckInGuest;
use Illuminate\Foundation\Http\FormRequest;
final class CheckInGuestRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()?->can('check-in-guests') ?? false;
}
/**
* @return array<string, list<mixed>>
*/
public function rules(): array
{
return [];
}
}The gate is defined in ReservationsServiceProvider, next to the three new command mappings. It relies on the users table having a boolean is_staff column, which is true for front-desk accounts:
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Models\User;
use App\Reservations\CancelReservation\CancelReservationCommand;
use App\Reservations\CancelReservation\CancelReservationCommandHandler;
use App\Reservations\ChangeReservationDates\ChangeReservationDatesCommand;
use App\Reservations\ChangeReservationDates\ChangeReservationDatesCommandHandler;
use App\Reservations\CheckInGuest\CheckInGuestCommand;
use App\Reservations\CheckInGuest\CheckInGuestCommandHandler;
use App\Reservations\ListReservations\ListReservationsQuery;
use App\Reservations\ListReservations\ListReservationsQueryHandler;
use App\Reservations\RequestReservation\RequestReservationCommand;
use App\Reservations\RequestReservation\RequestReservationCommandHandler;
use App\Reservations\RequestReservation\ReservationConfirmed;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
final class ReservationsServiceProvider extends ServiceProvider
{
public function boot(): void
{
Bus::map([
RequestReservationCommand::class => RequestReservationCommandHandler::class,
ListReservationsQuery::class => ListReservationsQueryHandler::class,
CancelReservationCommand::class => CancelReservationCommandHandler::class,
CheckInGuestCommand::class => CheckInGuestCommandHandler::class,
ChangeReservationDatesCommand::class => ChangeReservationDatesCommandHandler::class,
]);
Gate::define('check-in-guests', fn (User $user): bool => (bool) $user->is_staff);
Event::listen(ReservationConfirmed::class, SendReservationConfirmation::class);
$this->loadRoutesFrom(__DIR__.'/reservations-routes.php');
}
}A guest sending POST /api/reservations/42/check-in gets a 403 before any handler runs, and there is no body to smuggle a different intent through.
Changing dates is the one slice with a payload. Its command carries the two dates and the handler reprices, the same work the old controller did inside its first if:
<?php
declare(strict_types=1);
namespace App\Reservations\ChangeReservationDates;
final readonly class ChangeReservationDatesCommand
{
public function __construct(
public int $reservationId,
public string $checkIn,
public string $checkOut,
) {
}
}<?php
declare(strict_types=1);
namespace App\Reservations\ChangeReservationDates;
use App\Pricing\NightlyRatePricing;
use App\Reservations\Reservation\Reservation;
use Carbon\CarbonImmutable;
final readonly class ChangeReservationDatesCommandHandler
{
public function __construct(
private NightlyRatePricing $pricing,
) {
}
public function handle(ChangeReservationDatesCommand $command): void
{
$reservation = Reservation::query()
->with('room.roomType')
->findOrFail($command->reservationId);
$checkIn = CarbonImmutable::parse($command->checkIn);
$checkOut = CarbonImmutable::parse($command->checkOut);
$reservation->changeDates(
checkIn: $checkIn,
checkOut: $checkOut,
totalCents: $this->pricing->totalCents($reservation->room->roomType, $checkIn, $checkOut),
);
}
}Its controller still type-hints the shared ReservationRequest for now. The next lesson gives it a request of its own.
The dates and check-in routes replace the old PATCH line in reservations-routes.php, and ChangeReservation/ is deleted. The routes read like the operations.
<?php
declare(strict_types=1);
use App\Reservations\CancelReservation\CancelReservationController;
use App\Reservations\ChangeReservationDates\ChangeReservationDatesController;
use App\Reservations\CheckInGuest\CheckInGuestController;
use App\Reservations\ImportChannelReservations\ImportChannelReservationsController;
use App\Reservations\ListReservations\ListReservationsController;
use App\Reservations\RequestReservation\RequestReservationController;
use App\Reservations\ShowReservation\ShowReservationController;
use Illuminate\Support\Facades\Route;
Route::prefix('api')->middleware(['api', 'auth:sanctum'])->group(function (): void {
Route::get('/reservations', ListReservationsController::class)->name('reservations.list');
Route::post('/reservations', RequestReservationController::class)->name('reservations.request');
Route::get('/reservations/{id}', ShowReservationController::class)->name('reservations.show');
Route::patch('/reservations/{id}/dates', ChangeReservationDatesController::class)
->name('reservations.dates.change');
Route::post('/reservations/{id}/cancel', CancelReservationController::class)
->name('reservations.cancel');
Route::post('/reservations/{id}/check-in', CheckInGuestController::class)
->name('reservations.check-in');
Route::post('/reservations/import', ImportChannelReservationsController::class)->name('reservations.import');
});The one thing to remember
An HTTP verb describes transport, not intent. When one endpoint serves several intents, everything specific to each intent (its rules, its permission check, its allowed transitions) has nowhere to live except a chain of if statements. Give each intent its own URL with its own command and request, and each of those things gets exactly one place.