Skip to content

Refactoring Ergodnc - Business Logic Out of a Laravel Controller

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 POST /reservations endpoint, 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 endpoint is registered at routes/api.php:40 with the auth:sanctum and verified middleware, and the whole flow is the create method at app/Http/Controllers/UserReservationController.php:52-118:

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 cancel() omitted public function create() { abort_unless(auth()->user()->tokenCan('reservations.make'), Response::HTTP_FORBIDDEN ); $data = validator(request()->all(), [ 'office_id' => ['required', 'integer'], 'start_date' => ['required', 'date:Y-m-d', 'after:today'], 'end_date' => ['required', 'date:Y-m-d', 'after:start_date'], ])->validate(); try { $office = Office::findOrFail($data['office_id']); } catch (ModelNotFoundException $e) { throw ValidationException::withMessages([ 'office_id' => 'Invalid office_id' ]); } if ($office->user_id == auth()->id()) { throw ValidationException::withMessages([ 'office_id' => 'You cannot make a reservation on your own office' ]); } if ($office->hidden || $office->approval_status == Office::APPROVAL_PENDING) { throw ValidationException::withMessages([ 'office_id' => 'You cannot make a reservation on a hidden office' ]); } $reservation = Cache::lock('reservations_office_'.$office->id, 10)->block(3, function () use ($data, $office) { $numberOfDays = Carbon::parse($data['end_date'])->endOfDay()->diffInDays( Carbon::parse($data['start_date'])->startOfDay() ) + 1; if ($office->reservations()->activeBetween($data['start_date'], $data['end_date'])->exists()) { throw ValidationException::withMessages([ 'office_id' => 'You cannot make a reservation during this time' ]); } $price = $numberOfDays * $office->price_per_day; if ($numberOfDays >= 28 && $office->monthly_discount) { $price = $price - ($price * $office->monthly_discount / 100); } return Reservation::create([ 'user_id' => auth()->id(), 'office_id' => $office->id, 'start_date' => $data['start_date'], 'end_date' => $data['end_date'], 'status' => Reservation::STATUS_ACTIVE, 'price' => $price, 'wifi_password' => Str::random() ]); }); Notification::send(auth()->user(), new NewUserReservation($reservation)); Notification::send($office->user, new NewHostReservation($reservation)); return ReservationResource::make( $reservation->load('office') ); } }

Read top to bottom, the method checks a token ability, validates input, loads an office, rejects the guest's own office, rejects hidden or pending offices, takes a lock, counts the days, checks for an overlapping active reservation, prices the stay, applies a monthly discount, inserts the row, and sends two notifications. Every one of those steps is a decision or a side effect, and every one of them lives in the HTTP layer.

The model on the other side of this is app/Models/Reservation.php. It has two int constants at lines 13-14, casts at 16-22, two relations, and two query scopes at 34-52. It has no method that makes a reservation. The Office model at app/Models/Office.php:35-38 holds a reservations() relation, which is how the controller reaches across to check for conflicts at line 89.

What is wrong with it

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

  • The controller holds the business rules. The own-office check, the hidden-or-pending check, the day count, the price, and the 28-day discount (lines 72-99) are decisions that belong to the model that owns the data.

  • The reservation is built as an array and mass-assigned (lines 101-109), so no class owns what a new reservation is.

  • Validation is inline through the validator() helper (lines 58-62) instead of a Form Request. Its date:Y-m-d is not a format rule: date takes no parameters, so any parseable date passes.

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

  • A missing office becomes a 422 validation error. The controller calls findOrFail() and then catches the ModelNotFoundException it throws (lines 64-70), so the 404 never happens.

  • Cache, Notification, auth(), request(), and validator() resolve their dependencies from the container globally, so the class hides what it needs.

  • The controller sends both notifications itself and dispatches no event (lines 112-113), so anything else that needs to react to a new reservation has to be added to the controller.

  • The lock key is built inline from the raw string 'reservations_office_' (line 84).

  • The status is the int constant Reservation::STATUS_ACTIVE (line 106, Reservation.php:13), stored as an integer, not an enum case.

  • Office holds a HasMany to reservations (Office.php:35-38), and the controller walks it to check for conflicts (line 89). Reservation points back with office() and user() (Reservation.php:24-32), the controller reaches the host through $office->user (line 113), and the response loads the office (line 116). Offices and reservations are separate capabilities, and these relations fuse them.

  • ReservationResource spreads every column of the model and nests the office (app/Http/Resources/ReservationResource.php:18-24), so any new column leaks into the response.

  • Both notifications are queued but never say which queue, carry the whole Reservation model, and still send the scaffold text "The introduction to the notification."

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

  • The method returns a resource with no status. The 201 comes from Laravel noticing that the model wasRecentlyCreated, so it is right by accident.

The refactor

The rebuild splits the app into three modules: Reservations, Offices, and Identity, which owns the User model, login, and tokens. A Shared folder holds only the queue-name enum. Everything this endpoint needs moves out of Laravel's type folders into one slice folder, ReserveOffice/. What other slices share sits next to it: the model, its value objects, and its domain exceptions in Reservation/ (their base class sits at the module root), and the interfaces Reservations needs from other modules in Contracts/.

Before, at commit 42907c0:

TEXT
app/ Http/ Kernel.php Controllers/UserReservationController.php Resources/ReservationResource.php Models/ Office.php Reservation.php User.php Notifications/ NewHostReservation.php NewUserReservation.php Providers/ AppServiceProvider.php routes/ api.php database/migrations/ 2021_09_09_124300_create_reservations_table.php

After the rebuild:

TEXT
app/ Reservations/ ReservationAbility.php ReservationsException.php ReservationsServiceProvider.php reservations-routes.php BackfillReservationHosts/ BackfillReservationHosts.php Contracts/ ReservableOffice.php ReservableOffices.php ReservationContacts.php Reservation/ CannotReserveOwnOfficeException.php OfficeAlreadyReservedException.php OfficeNotReservableException.php Reservation.php ReservationFactory.php ReservationLock.php ReservationStatus.php Stay.php StayPrice.php ReserveOffice/ GuestReservationConfirmation.php HostReservationNotice.php NotifyGuestAndHostListener.php OfficeReserved.php ReserveOfficeCommand.php ReserveOfficeCommandHandler.php ReserveOfficeController.php ReserveOfficeRequest.php ReserveOfficeResource.php ReserveOfficeResult.php Offices/ OfficesServiceProvider.php Integrations/ OfficesForReservations.php Office/ Office.php OfficeApprovalStatus.php Identity/ IdentityServiceProvider.php Integrations/ ContactsForReservations.php User/ User.php Shared/ Queue/ QueueName.php bootstrap/ app.php providers.php database/migrations/ 2026_10_12_000001_add_host_user_id_to_reservations_table.php 2026_10_12_000002_make_host_user_id_required_on_reservations_table.php 2026_10_12_000003_convert_reservation_status_to_string.php

Pricing

Stay is the inclusive day range. Its constructor refuses a stay that ends before it starts, so no other class has to check:

PHP
<?php declare(strict_types=1); namespace App\Reservations\Reservation; use Carbon\CarbonImmutable; use InvalidArgumentException; final readonly class Stay { private const INCLUDE_LAST_DAY = 1; public function __construct( public CarbonImmutable $start, public CarbonImmutable $end, ) { if ($this->end->lessThan($this->start)) { throw new InvalidArgumentException('A stay cannot end before it starts.'); } } public static function fromDates(string $start, string $end): self { return new self( CarbonImmutable::parse($start)->startOfDay(), CarbonImmutable::parse($end)->startOfDay(), ); } public function days(): int { return (int) $this->start->diffInDays($this->end) + self::INCLUDE_LAST_DAY; } }

A stay from the 1st to the 10th is ten days. The original got the same count by measuring from the end of the last day back to the start of the first and adding one (UserReservationController.php:85-87).

StayPrice owns the rate rule and the 28-day discount rule, so pricing can be unit tested with no database and no HTTP request.

PHP
<?php declare(strict_types=1); namespace App\Reservations\Reservation; final readonly class StayPrice { public const MONTHLY_DISCOUNT_MINIMUM_DAYS = 28; private const PERCENT_BASE = 100; private function __construct( private int $amount, ) { } public static function for(Stay $stay, int $pricePerDay, int $monthlyDiscount): self { $days = $stay->days(); $amount = $days * $pricePerDay; if ($days >= self::MONTHLY_DISCOUNT_MINIMUM_DAYS && $monthlyDiscount > 0) { $amount -= (int) round($amount * $monthlyDiscount / self::PERCENT_BASE); } return new self($amount); } public function amount(): int { return $this->amount; } }

The original can produce a float at line 98 (any discount that does not divide the total evenly) and hands it to an integer column, so the rounding is whatever the database does with a float. The value object rounds explicitly and returns an int, so the price ergodnc's own test checks (40 days at 1,000 per day with 10 percent off is 36,000) is decided in PHP, where a unit test can see it.

The int constants at Reservation.php:13-14 become a ReservationStatus string enum, ACTIVE = 'active' and CANCELLED = 'cancelled', with a label() for display. A migration changes the column to a string with a default of 'active' and converts the stored 1 and 2 to the new strings. The lock lives in one place too: ReservationLock::forOffice($officeId) builds the key, and the class holds the two timings as constants instead of bare numbers in the code.

The contract with the Offices module

The Reservations module says what it needs from an office. The Offices module decides how to provide it. That replaces the HasMany that fused the two modules. Whether an office is open for booking stays the Offices module's decision, because approval and visibility are its data. The price and the open flag are read through the contract at booking time instead of being copied into a Reservations table, on purpose: a copy of the price could only be stale, and booking is the one moment it has to be current.

PHP
<?php declare(strict_types=1); namespace App\Reservations\Contracts; use Illuminate\Database\Eloquent\ModelNotFoundException; interface ReservableOffices { /** * @throws ModelNotFoundException when the office does not exist */ public function findOrFail(int $officeId): ReservableOffice; }

ReservableOffice is a readonly object with five public properties: id, hostUserId, pricePerDay, monthlyDiscount, and isOpenForReservations. A missing office surfaces as Eloquent's ModelNotFoundException, which Laravel renders as the 404 the original swallowed.

The implementation lives in the Offices module and uses that module's own Eloquent model:

PHP
<?php declare(strict_types=1); namespace App\Offices\Integrations; use App\Offices\Office\Office; use App\Reservations\Contracts\ReservableOffice; use App\Reservations\Contracts\ReservableOffices; final readonly class OfficesForReservations implements ReservableOffices { public function findOrFail(int $officeId): ReservableOffice { $office = Office::query()->findOrFail($officeId); return new ReservableOffice( id: $office->id, hostUserId: $office->user_id, pricePerDay: $office->price_per_day, monthlyDiscount: $office->monthly_discount, isOpenForReservations: $office->isOpenForReservations(), ); } }

isOpenForReservations() is a method on the Offices Office model that returns true for an approved office that is not hidden, the condition from line 78. It compares approval_status with an OfficeApprovalStatus enum that replaces Office::APPROVAL_PENDING and APPROVAL_APPROVED at Office.php:18-19. OfficesServiceProvider binds ReservableOffices to OfficesForReservations.

The Reservation model

PHP
<?php declare(strict_types=1); namespace App\Reservations\Reservation; use App\Reservations\Contracts\ReservableOffice; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Str; /** * @use HasFactory<ReservationFactory> */ final class Reservation extends Model { use HasFactory; public static function reserve(int $guestUserId, ReservableOffice $office, Stay $stay): self { if ($office->hostUserId === $guestUserId) { throw new CannotReserveOwnOfficeException(); } if (! $office->isOpenForReservations) { throw OfficeNotReservableException::forOffice($office->id); } if (self::officeIsReservedDuring($office->id, $stay)) { throw new OfficeAlreadyReservedException(); } $reservation = new self(); $reservation->user_id = $guestUserId; $reservation->office_id = $office->id; $reservation->host_user_id = $office->hostUserId; $reservation->start_date = $stay->start; $reservation->end_date = $stay->end; $reservation->status = ReservationStatus::ACTIVE; $reservation->price = StayPrice::for($stay, $office->pricePerDay, $office->monthlyDiscount)->amount(); $reservation->wifi_password = Str::random(); $reservation->save(); return $reservation; } private static function officeIsReservedDuring(int $officeId, Stay $stay): bool { return self::query() ->where('office_id', $officeId) ->where('status', ReservationStatus::ACTIVE) ->betweenDates($stay->start->toDateString(), $stay->end->toDateString()) ->exists(); } /** * @param Builder<Reservation> $query * @return Builder<Reservation> */ public function scopeBetweenDates(Builder $query, string $from, string $to): Builder { return $query->where(function (Builder $query) use ($from, $to): void { $query ->whereBetween('start_date', [$from, $to]) ->orWhereBetween('end_date', [$from, $to]) ->orWhere(function (Builder $query) use ($from, $to): void { $query ->where('start_date', '<', $from) ->where('end_date', '>', $to); }); }); } // Methods used by other slices, such as cancel(), are omitted. protected static function newFactory(): ReservationFactory { return ReservationFactory::new(); } /** * @return array<string, string> */ protected function casts(): array { return [ 'user_id' => 'integer', 'office_id' => 'integer', 'host_user_id' => 'integer', 'price' => 'integer', 'status' => ReservationStatus::class, 'start_date' => 'immutable_date', 'end_date' => 'immutable_date', 'wifi_password' => 'encrypted', ]; } }

Three things changed against app/Models/Reservation.php. The office() and user() relations at lines 24-32 are gone; office_id, user_id, and host_user_id are plain columns. The three-branch date condition from scopeBetweenDates at lines 40-52 stays as a scope, and the private officeIsReservedDuring() wraps it so reserve() asks a question instead of composing scopes. And the model has a named constructor that owns what a new reservation is: the three checks from lines 72, 78, and 89, in the original order, then the write. There is no $fillable, because Model::unguard() is already global in ergodnc at app/Providers/AppServiceProvider.php:31.

The three domain errors extend one base class that renders itself, so no controller builds an error response:

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

CannotReserveOwnOfficeException and OfficeNotReservableException are input problems, so they keep the default 422. OfficeAlreadyReservedException is a conflict with existing state, so it sets $status to Response::HTTP_CONFLICT (409).

host_user_id is new. The Reservations module needs the Host's id to notify them but does not own offices, so the reservation stores its own copy, taken from the ReservableOffice at booking time. An office never changes host (OfficeController.php:75 sets user_id once, and the update validator has no user_id rule), so nothing has to keep the copy in sync. A migration must not touch another module's table, so the backfill runs in three steps: a migration adds the column as nullable, a one-off BackfillReservationHosts console command fills it by reading each office's user_id by id through an injected ConnectionInterface, and a second migration makes the column required. No foreign key is declared, because offices belongs to another module.

Command and handler

ReserveOfficeCommand is a readonly object with four scalars: guestUserId, officeId, startDate, and endDate. The handler coordinates: resolve the office, build the stay, take the lock, ask the model to reserve, dispatch the fact.

PHP
<?php declare(strict_types=1); namespace App\Reservations\ReserveOffice; use App\Reservations\Contracts\ReservableOffices; use App\Reservations\Reservation\Reservation; use App\Reservations\Reservation\ReservationLock; use App\Reservations\Reservation\Stay; use Illuminate\Contracts\Cache\LockProvider; use Illuminate\Contracts\Events\Dispatcher; final readonly class ReserveOfficeCommandHandler { public function __construct( private ReservableOffices $offices, private LockProvider $locks, private Dispatcher $events, ) { } public function handle(ReserveOfficeCommand $command): ReserveOfficeResult { $office = $this->offices->findOrFail($command->officeId); $stay = Stay::fromDates($command->startDate, $command->endDate); $reservation = $this->locks ->lock(ReservationLock::forOffice($office->id), ReservationLock::HOLD_SECONDS) ->block( ReservationLock::WAIT_SECONDS, fn (): Reservation => Reservation::reserve($command->guestUserId, $office, $stay), ); $this->events->dispatch(new OfficeReserved( reservationId: $reservation->id, guestUserId: $reservation->user_id, officeId: $reservation->office_id, )); return new ReserveOfficeResult($reservation); } }

The lock timings are the ones from line 84: hold for ten seconds, wait up to three. The lock stays in the handler because it is coordination, not a business rule. The handler has no branch: the three checks and the write all happen inside Reservation::reserve(), under the lock.

The handler returns a ReserveOfficeResult, a readonly DTO whose one property, reservation, is the model it just created. Copying the nine columns into properties of their own would change nothing the client sees, so the resource reads them from the model.

Form Request and controller

PHP
<?php declare(strict_types=1); namespace App\Reservations\ReserveOffice; use Illuminate\Foundation\Http\FormRequest; final class ReserveOfficeRequest extends FormRequest { public function authorize(): bool { return true; } /** * @return array<string, list<string>> */ public function rules(): array { return [ 'office_id' => ['required', 'integer'], 'start_date' => ['required', 'date_format:Y-m-d', 'after:today'], 'end_date' => ['required', 'date_format:Y-m-d', 'after:start_date'], ]; } public function officeId(): int { return $this->integer('office_id'); } public function startDate(): string { return $this->string('start_date')->toString(); } public function endDate(): string { return $this->string('end_date')->toString(); } }

authorize() returns true on purpose. Authentication is the route middleware, and the only authorization question in this flow (can this Guest book this office) is the own-office rule, which the model owns.

PHP
<?php declare(strict_types=1); namespace App\Reservations\ReserveOffice; use Illuminate\Contracts\Bus\Dispatcher; use Illuminate\Http\JsonResponse; use Knuckles\Scribe\Attributes\Authenticated; use Knuckles\Scribe\Attributes\Endpoint; use Knuckles\Scribe\Attributes\Group; use Knuckles\Scribe\Attributes\Response; use Symfony\Component\HttpFoundation\Response as SymfonyResponse; #[Group('Reservations')] final readonly class ReserveOfficeController { public function __construct( private Dispatcher $bus, ) { } #[Endpoint('Reserve an office', 'Books an approved, visible office for the authenticated guest.')] #[Authenticated] #[Response( content: [ 'data' => [ 'id' => 42, 'office_id' => 7, 'user_id' => 3, 'start_date' => '2026-11-02T00:00:00+00:00', 'end_date' => '2026-11-06T00:00:00+00:00', 'status' => 'active', 'price' => 5000, 'wifi_password' => 'pQ7rT2vXk9LmZa4B', 'created_at' => '2026-10-20T09:14:03+00:00', ], ], status: SymfonyResponse::HTTP_CREATED, )] public function __invoke(ReserveOfficeRequest $request): JsonResponse { $result = $this->bus->dispatch(new ReserveOfficeCommand( guestUserId: $request->user()->id, officeId: $request->officeId(), startDate: $request->startDate(), endDate: $request->endDate(), )); return ReserveOfficeResource::make($result) ->response() ->setStatusCode(SymfonyResponse::HTTP_CREATED); } }

The Guest's id comes from $request->user(), never from the body. The controller reads it through the auth guard, so it never imports Identity's User class. The Scribe attributes document the endpoint, with a #[Response] example that has the same nine keys as the resource.

The original ReservationResource at app/Http/Resources/ReservationResource.php:18-24 spreads every column of the model and nests the office. ReserveOfficeResource is a plain JsonResource over the ReserveOfficeResult and reads the reservation through it. Its toArray() names nine keys (id, office_id, user_id, start_date, end_date, status, price, wifi_password, created_at), with every date serialised through toIso8601String() and the status as its string value.

Event, listener, notifications

Notifying the Guest and the Host is a consequence of the reservation, so the handler dispatches OfficeReserved and a listener sends the notifications. Anything else that needs to react to a new reservation adds a listener instead of editing the handler. The event is a readonly object carrying three ids, reservationId, guestUserId, and officeId, not models.

The listener needs two email addresses, and users belong to Identity. So Reservations defines what it needs, the same way it does for offices:

PHP
<?php declare(strict_types=1); namespace App\Reservations\Contracts; interface ReservationContacts { public function emailOf(int $userId): string; }

Identity implements it in ContactsForReservations, a lookup on its own User model, and binds it in IdentityServiceProvider. The listener sends on-demand notifications to those addresses, so it never touches a User:

PHP
<?php declare(strict_types=1); namespace App\Reservations\ReserveOffice; use App\Reservations\Contracts\ReservationContacts; use App\Reservations\Reservation\Reservation; use Illuminate\Contracts\Notifications\Dispatcher; use Illuminate\Notifications\AnonymousNotifiable; final readonly class NotifyGuestAndHostListener { public function __construct( private ReservationContacts $contacts, private Dispatcher $notifications, ) { } public function handle(OfficeReserved $event): void { $reservation = Reservation::query()->findOrFail($event->reservationId); $guest = (new AnonymousNotifiable())->route('mail', $this->contacts->emailOf($reservation->user_id)); $host = (new AnonymousNotifiable())->route('mail', $this->contacts->emailOf($reservation->host_user_id)); $this->notifications->send($guest, new GuestReservationConfirmation($reservation->id)); $this->notifications->send($host, new HostReservationNotice($reservation->id)); } }

GuestReservationConfirmation and HostReservationNotice replace NewUserReservation and NewHostReservation from app/Notifications/. Here is the Guest's:

PHP
<?php declare(strict_types=1); namespace App\Reservations\ReserveOffice; use App\Reservations\Reservation\Reservation; use App\Shared\Queue\QueueName; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; final class GuestReservationConfirmation extends Notification implements ShouldQueue { use Queueable; private const MAX_ATTEMPTS = 3; private const RETRY_DELAY_SECONDS = 60; public int $tries = self::MAX_ATTEMPTS; public int $backoff = self::RETRY_DELAY_SECONDS; public function __construct( public int $reservationId, ) { $this->onQueue(QueueName::NOTIFICATIONS->value); } /** * @return list<string> */ public function via(object $notifiable): array { return ['mail']; } public function toMail(object $notifiable): MailMessage { $reservation = Reservation::query()->findOrFail($this->reservationId); return (new MailMessage()) ->subject('Your reservation is confirmed') ->line("Your office is booked from {$reservation->start_date->toDateString()} to {$reservation->end_date->toDateString()}.") ->line("The Wi-Fi password is {$reservation->wifi_password}."); } }

It sets its queue through the shared QueueName enum, declares $tries and $backoff because it talks to a mail server, takes a reservation id instead of the model, loads the reservation in toMail(), and sends a real subject and body. HostReservationNotice has the same shape, with the subject "You have a new reservation" and no Wi-Fi password.

Route and wiring

The ability strings become constants on ReservationAbility, such as ReservationAbility::MAKE = 'reservations.make', and the route checks them with middleware instead of abort_unless in the controller.

PHP
<?php declare(strict_types=1); use App\Reservations\ReservationAbility; use App\Reservations\ReserveOffice\ReserveOfficeController; use Illuminate\Support\Facades\Route; // Routes from the other slices in this module are omitted. Route::post('/reservations', ReserveOfficeController::class) ->middleware(['auth:sanctum', 'verified', 'abilities:'.ReservationAbility::MAKE]) ->name('reservations.reservations.reserve');

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.

ReservationsServiceProvider wires the slice: the command to its handler, the listener to its event, and the route file inside the api middleware group.

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Reservations\ReserveOffice\NotifyGuestAndHostListener; use App\Reservations\ReserveOffice\OfficeReserved; use App\Reservations\ReserveOffice\ReserveOfficeCommand; use App\Reservations\ReserveOffice\ReserveOfficeCommandHandler; use Illuminate\Contracts\Cache\Factory as CacheFactory; use Illuminate\Contracts\Cache\LockProvider; use Illuminate\Contracts\Foundation\Application; use Illuminate\Support\Facades\Bus; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Route; use Illuminate\Support\ServiceProvider; final class ReservationsServiceProvider extends ServiceProvider { // Bindings, Bus::map() entries, and listeners from the other slices are omitted. public function register(): void { $this->app->bind( LockProvider::class, fn (Application $app): LockProvider => $app->make(CacheFactory::class)->store()->getStore(), ); } public function boot(): void { Bus::map([ ReserveOfficeCommand::class => ReserveOfficeCommandHandler::class, ]); Event::listen(OfficeReserved::class, NotifyGuestAndHostListener::class); Route::middleware('api')->group(__DIR__.'/reservations-routes.php'); } }

It binds LockProvider to the store behind the default cache repository, because Laravel binds the repository contract but not LockProvider, and the repository itself has no lock() method. All three module providers are registered in bootstrap/providers.php. Facades are fine in providers, route files, and migrations; production classes get their dependencies injected.

What changed in the API contract

  • start_date and end_date must be Y-m-d. The original accepted any parseable date: the date rule takes no parameters, so the :Y-m-d suffix at UserReservationController.php:60-61 is ignored.

  • A missing office returns 404 with {"message": "No query results for model [App\\Offices\\Office\\Office] 7"} instead of a 422 validation error keyed on office_id.

  • A token without the reservations.make ability still gets a 403, now with the message "Invalid ability provided." from Sanctum's middleware.

  • A hidden or pending office returns 422 with {"message": "Office 7 is not open for reservations."} instead of a validation error keyed on office_id.

  • Reserving your own office returns 422 with a bare message instead of a validation error keyed on office_id.

  • An overlapping active reservation returns 409 instead of 422.

  • The response body lists nine named keys. It no longer embeds the office, and it no longer spreads every model column.

  • status is "active" or "cancelled" instead of 1 or 2, and dates change format from 2026-11-02T00:00:00.000000Z to 2026-11-02T00:00:00+00:00.

  • A discount that leaves half a unit is rounded in PHP, so the stored price can differ by one from what the database stored before. Twenty-nine days at 5 per day with 10 percent off now stores 130; the original handed the database 130.5.

  • The 201 is set explicitly rather than inferred from wasRecentlyCreated.

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 feature tests still expect the old 422s (UserReservationControllerTest.php:203, :224), so both need work before this ships. More will come up once the code is in use. What matters is that each rule now sits where the next change will look for it: the price in StayPrice, the three checks in Reservation::reserve(), and the emails in a listener.