Skip to content

Refactoring Ergodnc - Putting the Ownership Check Inside the Lookup

Code Reviews•
October 12, 2026

Ergodnc is the office-rental API Mohamed Said built live on the official Laravel YouTube channel (themsaid/ergodnc, read at commit 42907c0). This piece shows its DELETE /reservations/{reservation} endpoint, where a Guest cancels a reservation they made, what is wrong with it, and a rebuild as a vertical slice with a domain model.

Ergodnc runs Laravel 8. The rebuild targets Laravel 13.

What the endpoint does today

The route is Route::delete('/reservations/{reservation}', [UserReservationController::class, 'cancel'])->middleware(['auth:sanctum', 'verified']); at routes/api.php:41. The handler is the cancel method at app/Http/Controllers/UserReservationController.php:120-141:

PHP
<?php namespace App\Http\Controllers; use App\Http\Resources\ReservationResource; use App\Models\Office; use App\Models\Reservation; use App\Notifications\NewHostReservation; use App\Notifications\NewUserReservation; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Str; use Illuminate\Validation\Rule; use Illuminate\Validation\ValidationException; class UserReservationController extends Controller { // index() and create() omitted public function cancel(Reservation $reservation) { abort_unless(auth()->user()->tokenCan('reservations.cancel'), Response::HTTP_FORBIDDEN ); if ($reservation->user_id != auth()->id() || $reservation->status == Reservation::STATUS_CANCELLED || $reservation->start_date < now()->toDateString()) { throw ValidationException::withMessages([ 'reservation' => 'You cannot cancel this reservation' ]); } $reservation->update([ 'status' => Reservation::STATUS_CANCELLED ]); return ReservationResource::make( $reservation->load('office') ); } }

The if carries three decisions: the caller owns the reservation (line 126), it is not already cancelled (line 127), and it has not started (line 128). All three end in the same ValidationException with the same message, so a client that sent someone else's id, a stale id, or the id of a stay that began yesterday gets the same 422.

What is wrong with it

  • There is no slice and no command. UserReservationController has three actions (index, create, cancel), and the pieces of this endpoint sit in Laravel's type folders: app/Http/Controllers, app/Models, app/Http/Resources.

  • Reservation $reservation is route-model binding (UserReservationController.php:120, routes/api.php:41). Laravel loads the row for any id before the controller runs, so there is no place to scope the lookup to the caller.

  • Ownership is "fetch by id, then compare" (line 126). The check lives in the caller, one || clause away from being edited out, and the rebuild moves it inside the lookup.

  • A non-owner gets a 422 validation error under the key reservation where a 403 belongs (lines 126-132). The three failure reasons share one status and one message.

  • The controller reads status and start_date and decides for the model (lines 126-128), then writes the new status itself with update(['status' => ...]) (line 134). No method on Reservation owns what cancelling means.

  • Line 128 compares an immutable date object with the string now()->toDateString() using <. It works because PHP converts the object to Y-m-d H:i:s and compares strings, so a stay that starts today is still cancellable, but only by accident of string ordering.

  • The ability is the string 'reservations.cancel', checked inline with abort_unless (line 122), so the controller builds its own 403 instead of leaving it to ability middleware with a constant.

  • auth() and now() (lines 122, 126, 128) resolve their dependencies globally, so the class hides what it needs.

  • The endpoint returns 200 with the reservation and its loaded office (line 138). ReservationResource spreads every column of the model and nests the office (app/Http/Resources/ReservationResource.php:18-24), so any new column leaks into a response that only needed to confirm a cancellation.

  • Reservation carries user() and office() relations (app/Models/Reservation.php:24-32), which is how line 139 reaches across to the office. Reservations and offices are separate capabilities, and the relations fuse them.

  • The status is the int constants STATUS_ACTIVE and STATUS_CANCELLED (Reservation.php:13-14) with an integer cast, not an enum.

  • Cancelling dispatches nothing, so anything that should react to a cancellation has to be added to the controller.

  • The route has no name (routes/api.php:41).

The refactor

The rebuild is one slice, App\Reservations\CancelReservation\, plus the parts of the Reservations module that other slices share. It imports nothing from App\Offices or App\Identity.

Before, at commit 42907c0:

TEXT
app/ Http/ Controllers/UserReservationController.php Kernel.php Resources/ReservationResource.php Models/Reservation.php routes/api.php database/migrations/2021_09_09_124300_create_reservations_table.php

After the rebuild:

TEXT
app/ Reservations/ CancelReservation/ CancelReservationCommand.php CancelReservationCommandHandler.php CancelReservationController.php ReservationCancelled.php Reservation/ Reservation.php ReservationAccessDeniedException.php ReservationCannotBeCancelledException.php ReservationStatus.php ReservationAbility.php ReservationsException.php ReservationsServiceProvider.php reservations-routes.php bootstrap/ app.php providers.php database/migrations/2026_10_12_000003_convert_reservation_status_to_string.php

The model owns the rules

Two questions used to live in the controller: may this caller touch this reservation, and may this reservation be cancelled. Both move to Reservation.

PHP
<?php declare(strict_types=1); namespace App\Reservations\Reservation; use Carbon\CarbonImmutable; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; /** * @use HasFactory<ReservationFactory> */ final class Reservation extends Model { use HasFactory; public static function findByIdForGuestOrFail(int $id, int $guestUserId): self { $reservation = self::query()->findOrFail($id); if ($reservation->user_id !== $guestUserId) { throw ReservationAccessDeniedException::forReservation($id); } return $reservation; } public function cancel(CarbonImmutable $today): void { if ($this->isCancelled()) { throw ReservationCannotBeCancelledException::alreadyCancelled($this->id); } if ($this->startedBefore($today)) { throw ReservationCannotBeCancelledException::alreadyStarted($this->id); } $this->status = ReservationStatus::CANCELLED; $this->save(); } public function isCancelled(): bool { return $this->status === ReservationStatus::CANCELLED; } private function startedBefore(CarbonImmutable $today): bool { return $this->start_date->lessThan($today); } // reserve(), scopeBetweenDates(), newFactory(), and the casts() method are omitted. }

findByIdForGuestOrFail() runs a plain findOrFail() first, so a missing id is still Laravel's 404. The ownership check comes right after, inside the same method, and throws a 403. No caller can get a Reservation for someone else's id without passing the gate. Ownership is checked before state, so a stranger probing a cancelled reservation learns nothing about its state.

cancel() takes today's date as an argument so the rule works for any date, and the handler supplies today. The two rules, already cancelled and already started, are the original's, in the original's order, but each now has its own exception. startedBefore() compares two CarbonImmutable values with lessThan(), so the date rule no longer depends on how PHP casts an object for <. A stay that starts today is still cancellable, as before.

The status is a ReservationStatus string enum (ACTIVE = 'active', CANCELLED = 'cancelled', with a label()), and the migration 2026_10_12_000003_convert_reservation_status_to_string.php changes the column to a string with a default of 'active' and rewrites the stored 1 and 2 to 'active' and 'cancelled'. The user() and office() relations are gone; user_id and office_id are plain columns.

The module's base exception renders itself, so no controller builds an error response. The status comes from Symfony's Response constants, and the default is 422.

PHP
<?php declare(strict_types=1); namespace App\Reservations; use Illuminate\Http\JsonResponse; use RuntimeException; use Symfony\Component\HttpFoundation\Response as SymfonyResponse; abstract class ReservationsException extends RuntimeException { protected int $status = SymfonyResponse::HTTP_UNPROCESSABLE_ENTITY; public function render(): JsonResponse { return new JsonResponse(['message' => $this->getMessage()], $this->status); } }

The ownership failure overrides the status to 403:

PHP
<?php declare(strict_types=1); namespace App\Reservations\Reservation; use App\Reservations\ReservationsException; use Symfony\Component\HttpFoundation\Response as SymfonyResponse; final class ReservationAccessDeniedException extends ReservationsException { protected int $status = SymfonyResponse::HTTP_FORBIDDEN; public static function forReservation(int $reservationId): self { return new self("You do not have access to reservation {$reservationId}."); } }

Already cancelled and already started are both conflicts with the reservation's current state, so one class with two named constructors keeps the 409 in one place while the message tells the client which rule it hit:

PHP
<?php declare(strict_types=1); namespace App\Reservations\Reservation; use App\Reservations\ReservationsException; use Symfony\Component\HttpFoundation\Response as SymfonyResponse; final class ReservationCannotBeCancelledException extends ReservationsException { protected int $status = SymfonyResponse::HTTP_CONFLICT; public static function alreadyCancelled(int $reservationId): self { return new self("Reservation {$reservationId} is already cancelled."); } public static function alreadyStarted(int $reservationId): self { return new self("Reservation {$reservationId} has already started and cannot be cancelled."); } }

Command and handler

The guest id in the command comes from the authenticated principal, never from the request.

PHP
<?php declare(strict_types=1); namespace App\Reservations\CancelReservation; final readonly class CancelReservationCommand { public function __construct( public int $reservationId, public int $guestUserId, ) { } }
PHP
<?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::findByIdForGuestOrFail($command->reservationId, $command->guestUserId); $reservation->cancel(CarbonImmutable::today()); $this->events->dispatch(new ReservationCancelled( reservationId: $reservation->id, officeId: $reservation->office_id, )); } }

The handler has no branch, because every if that used to sit in the controller is behind one of the two model calls. handle() returns nothing and there is no Result DTO, because the endpoint answers 204 with no body and no resource has anything to read.

The event carries ids only and is dispatched after the status is saved. Nothing listens to it, because the original ran nothing on a cancellation. It exists so a host notice or a refund can be added as a listener without editing the handler.

PHP
<?php declare(strict_types=1); namespace App\Reservations\CancelReservation; final readonly class ReservationCancelled { public function __construct( public int $reservationId, public int $officeId, ) { } }

Controller and route

The endpoint takes no body, so there is no Form Request, and the controller reads the Guest's id from the auth guard.

PHP
<?php declare(strict_types=1); namespace App\Reservations\CancelReservation; use Illuminate\Contracts\Bus\Dispatcher; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Knuckles\Scribe\Attributes\Authenticated; use Knuckles\Scribe\Attributes\Endpoint; use Knuckles\Scribe\Attributes\Group; use Knuckles\Scribe\Attributes\Response; use Knuckles\Scribe\Attributes\UrlParam; use Symfony\Component\HttpFoundation\Response as SymfonyResponse; #[Group('Reservations')] final readonly class CancelReservationController { public function __construct( private Dispatcher $bus, ) { } #[Endpoint('Cancel a reservation', 'Cancels an active reservation that the authenticated guest made and that has not started.')] #[Authenticated] #[UrlParam('reservationId', 'integer', 'The id of the reservation to cancel.', example: 42)] #[Response(status: SymfonyResponse::HTTP_NO_CONTENT, description: 'The reservation is cancelled.')] #[Response( content: ['message' => 'You do not have access to reservation 42.'], status: SymfonyResponse::HTTP_FORBIDDEN, )] #[Response( content: ['message' => 'Reservation 42 is already cancelled.'], status: SymfonyResponse::HTTP_CONFLICT, )] public function __invoke(Request $request, int $reservationId): JsonResponse { $this->bus->dispatch(new CancelReservationCommand( reservationId: $reservationId, guestUserId: $request->user()->id, )); return new JsonResponse(null, SymfonyResponse::HTTP_NO_CONTENT); } }

Laravel sends a 204 without a body even though JsonResponse is given null: Response::prepare() in Symfony empties the content for empty statuses.

The route lives in app/Reservations/reservations-routes.php, loaded by ReservationsServiceProvider inside the api middleware group. The ability is a typed constant, ReservationAbility::CANCEL, which keeps the stored token string 'reservations.cancel', so existing tokens still work. The route parameter is constrained to digits, so a non-numeric id is a 404 instead of a TypeError from the int parameter.

PHP
<?php declare(strict_types=1); use App\Reservations\CancelReservation\CancelReservationController; use App\Reservations\ReservationAbility; use Illuminate\Support\Facades\Route; // Routes from the other slices in this module are omitted. Route::delete('/reservations/{reservationId}', CancelReservationController::class) ->middleware(['auth:sanctum', 'verified', 'abilities:'.ReservationAbility::CANCEL]) ->whereNumber('reservationId') ->name('reservations.reservations.cancel');

The abilities alias points at Sanctum's CheckAbilities middleware and is registered in bootstrap/app.php. That file also calls $middleware->throttleApi(). Ergodnc throttles every API route (app/Http/Kernel.php:44), and in Laravel 13 the api group only does that when bootstrap/app.php asks for it. A token without reservations.cancel is now rejected at the route, before the reservation is loaded.

ReservationsServiceProvider, listed in bootstrap/providers.php, loads the route file inside the api middleware group and maps the command to its handler. Facades are fine in providers.

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Reservations\CancelReservation\CancelReservationCommand; use App\Reservations\CancelReservation\CancelReservationCommandHandler; use Illuminate\Support\Facades\Bus; use Illuminate\Support\Facades\Route; use Illuminate\Support\ServiceProvider; final class ReservationsServiceProvider extends ServiceProvider { // Bindings, other Bus::map() entries, and listeners from the other slices are omitted. public function boot(): void { Route::middleware('api')->group(__DIR__.'/reservations-routes.php'); Bus::map([ CancelReservationCommand::class => CancelReservationCommandHandler::class, ]); } }

What changed in the API contract

  • A successful cancel returns 204 with an empty body instead of 200 with the reservation and its office.

  • Cancelling someone else's reservation returns 403 with {"message": "You do not have access to reservation 42."} instead of a 422 validation error under the reservation key.

  • Cancelling an already-cancelled reservation returns 409 with {"message": "Reservation 42 is already cancelled."} instead of a 422.

  • Cancelling a reservation that has already started returns 409 with {"message": "Reservation 42 has already started and cannot be cancelled."} instead of a 422.

  • Ownership is checked before state. Someone else's cancelled or started reservation is a 403, where the original returned the same 422 for every case.

  • A non-numeric id such as abc returns 404 from the router with {"message": "The route reservations/abc could not be found."}, where the original's route-model binding returned No query results for model [App\\Models\\Reservation] abc.

  • A missing numeric reservation still returns 404, now with {"message": "No query results for model [App\\Reservations\\Reservation\\Reservation] 42"}.

  • A token without the reservations.cancel ability still gets a 403, now with the message "Invalid ability provided." from Sanctum's middleware instead of the empty message abort_unless produced. It is checked before the lookup, so a token without the ability gets a 403 even for an id that does not exist, where the original returned 404 first because route-model binding ran before the controller.

  • The URL, the verb, and the auth:sanctum and verified middleware are unchanged, and a reservation that starts today can still be cancelled.

A first pass

This is a first pass, and there is more I would change. The ids are still auto-increment integers, which the canon forbids, and the cancel endpoint had no tests to begin with, so both need work before this ships. More will come up once the code is in use. What matters is that the ownership check now lives inside Reservation::findByIdForGuestOrFail() and the cancel rules inside Reservation::cancel(), so each one has a single place to change.