Skip to content

Refactoring Ergodnc - From a Hand-Rolled Validator to Form Requests

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 two endpoints for putting an office on the platform, POST /offices (a host submits a new office) and PUT /offices/{office} (the host revises it), what is wrong with them, and a rebuild as two vertical slices with a domain model.

Ergodnc runs Laravel 8. The rebuild targets Laravel 13.

What the endpoints do today

Both routes sit at routes/api.php:30-31 behind auth:sanctum and verified. They are two methods of app/Http/Controllers/OfficeController.php: create() at lines 63-94 and update() at lines 96-127.

PHP
<?php namespace App\Http\Controllers; use App\Http\Resources\OfficeResource; use App\Models\Office; use App\Models\Reservation; use App\Models\User; use App\Models\Validators\OfficeValidator; use App\Notifications\OfficePendingApproval; use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Response; use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Storage; use Illuminate\Validation\Rule; use Illuminate\Validation\ValidationException; class OfficeController extends Controller { // index(), show(), and delete() omitted public function create(): JsonResource { abort_unless(auth()->user()->tokenCan('office.create'), Response::HTTP_FORBIDDEN ); $attributes = (new OfficeValidator())->validate( $office = new Office(), request()->all() ); $attributes['approval_status'] = Office::APPROVAL_PENDING; $attributes['user_id'] = auth()->id(); $office = DB::transaction(function () use ($office, $attributes) { $office->fill( Arr::except($attributes, ['tags']) )->save(); if (isset($attributes['tags'])) { $office->tags()->attach($attributes['tags']); } return $office; }); Notification::send(User::where('is_admin', true)->get(), new OfficePendingApproval($office)); return OfficeResource::make( $office->load(['images', 'tags', 'user']) ); } public function update(Office $office): JsonResource { abort_unless(auth()->user()->tokenCan('office.update'), Response::HTTP_FORBIDDEN ); $this->authorize('update', $office); $attributes = (new OfficeValidator())->validate($office, request()->all()); $office->fill(Arr::except($attributes, ['tags'])); if ($requiresReview = $office->isDirty(['lat', 'lng', 'price_per_day'])) { $office->fill(['approval_status' => Office::APPROVAL_PENDING]); } DB::transaction(function () use ($office, $attributes) { $office->save(); if (isset($attributes['tags'])) { $office->tags()->sync($attributes['tags']); } }); if ($requiresReview) { Notification::send(User::where('is_admin', true)->get(), new OfficePendingApproval($office)); } return OfficeResource::make( $office->load(['images', 'tags', 'user']) ); } }

Both methods validate through app/Models/Validators/OfficeValidator.php, a class the controller creates with new. One validator() call serves both endpoints, and Rule::when($office->exists, 'sometimes') makes six fields required on create and optional on update (lines 14-20). Ownership on update goes through app/Policies/OfficePolicy.php:13-16, which compares $user->id == $office->user_id. The {office} parameter is bound to a model by Laravel before the method runs.

What is wrong with it

  • There is no slice and no command. OfficeController holds five actions, and the pieces of these two endpoints sit in Laravel's type folders: app/Http/Controllers, app/Models/Validators, app/Policies, app/Notifications, app/Http/Resources.

  • The controller makes the decisions the Office should make about itself. It sets approval_status and user_id on an attribute array (OfficeController.php:74-75), fills the model and saves it (lines 77-87 and 106-118), and attaches or syncs tags inside the transaction closure (lines 82-84 and 115-117).

  • The most important rule in this flow, that a change to location or price sends an office back to pending approval, is an isDirty check inside an HTTP method (lines 108-110). Nothing outside this controller can apply it.

  • Validation is a hand-rolled class the controller creates with new (lines 69-72 and 104), wrapping the validator() helper (OfficeValidator.php:12), under a type-named folder inside the model namespace. Rule::when($office->exists, 'sometimes') is how one class serves two endpoints (lines 14-20), and the validator has to be handed an Office just to ask whether it exists.

  • The featured_image_id rule scopes the lookup to resource_id = $office->id (OfficeValidator.php:23). On create the office has no id yet, and a new office has no images, so any value sent fails with a 422.

  • The token abilities 'office.create' and 'office.update' are string literals checked with tokenCan() inside the method body (lines 65-67 and 98-100), so the controller builds its own 403 instead of leaving it to ability middleware with a constant.

  • {office} is route-model binding (routes/api.php:31, OfficeController.php:96), and the policy checks the owner after the model is already loaded (OfficePolicy.php:13-16, called at line 102). The policy compares the ids with loose == (line 15). The lookup and the ownership check are two separate steps, so a new endpoint can forget the second one.

  • No event exists. The controller sends the admin notification itself through the Notification facade, and the query that finds the admins is written twice (lines 89 and 121). It also imports App\Models\User to do it, so the office code reaches into the user model.

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

  • update() returns the full office with a 200 (lines 124-126). The 201 from create() comes from Laravel noticing that the model wasRecentlyCreated, so it is right by accident.

  • Approval status is two int constants on the model (Office.php:18-19), stored as integers, and the casts are a $casts property (lines 21-28).

  • Office holds a BelongsTo to the user (Office.php:30-33) and a HasMany to reservations (lines 35-38). Through them the office code reaches into Identity and Reservations.

  • OfficeResource merges parent::toArray() and subtracts four keys (OfficeResource.php:25-28), so any new column leaks into the response. It nests UserResource, which spreads every user column except four (UserResource.php:19-21), so the response exposes is_admin for the host. It also adds reservations_count (line 23).

  • OfficePendingApproval is queued but sets no queue, declares no $tries or $backoff, carries the whole Office model (OfficePendingApproval.php:20), and still sends the scaffold text "The introduction to the notification." (line 45).

  • The validator checks hidden with a bool rule (OfficeValidator.php:24). Laravel 8 has no such rule, only boolean, so any request that sends hidden throws and returns a 500.

  • Neither route has a name (routes/api.php:30-31).

The refactor

The rebuild splits ergodnc into modules, and both endpoints belong to App\Offices, one slice folder each. The Office model, its enum, its value objects, and its exceptions sit in Office/ because other slices use them too. Identity owns the User model, login, and tokens.

Before, at commit 42907c0:

TEXT
app/ Http/ Kernel.php Controllers/OfficeController.php Resources/ OfficeResource.php UserResource.php Models/ Image.php Office.php Tag.php User.php Validators/OfficeValidator.php Notifications/OfficePendingApproval.php Policies/OfficePolicy.php Providers/AppServiceProvider.php database/migrations/2021_09_09_124245_create_offices_table.php routes/api.php

After the rebuild:

TEXT
app/ Identity/ IdentityServiceProvider.php Integrations/AdminsForOffices.php User/User.php Offices/ OfficeAbility.php OfficesException.php OfficesServiceProvider.php offices-routes.php Contracts/OfficeAdmins.php Image/Image.php Tag/Tag.php Office/ Office.php OfficeFactory.php OfficeApprovalStatus.php OfficeDetails.php OfficeChanges.php OfficeAccessDeniedException.php SubmitOffice/ SubmitOfficeCommand.php SubmitOfficeCommandHandler.php SubmitOfficeResult.php SubmitOfficeController.php SubmitOfficeRequest.php SubmitOfficeResource.php TagResource.php OfficeSubmittedForApproval.php NotifyAdminsOfPendingOfficeListener.php OfficePendingApproval.php ReviseOffice/ ReviseOfficeCommand.php ReviseOfficeCommandHandler.php ReviseOfficeController.php ReviseOfficeRequest.php Shared/Queue/QueueName.php bootstrap/ app.php providers.php database/migrations/2026_10_12_000004_convert_office_approval_status_to_string.php

Image and Tag keep their own folders in the Offices module. The interface this slice needs from another module, OfficeAdmins, sits in Offices/Contracts/. QueueName is the only shared class.

Approval status and the office details

The int constants become an OfficeApprovalStatus string enum, PENDING = 'pending' and APPROVED = 'approved', with a label() for display. A migration (2026_10_12_000004_convert_office_approval_status_to_string.php) changes the approval_status column from tinyInteger to a string with a default of 'pending' and converts the stored 1 and 2.

The fields a host fills in travel together as OfficeDetails, a readonly value object with title, description, lat, lng, addressLine1, addressLine2 (nullable), pricePerDay, monthlyDiscount, hidden, featuredImageId (nullable), and tagIds. Coordinates are strings because the columns are decimal(11, 8) and the decimal:8 cast yields strings. submit() takes one OfficeDetails instead of an array, so no caller can pass an unvalidated bag of keys.

Revise keeps the original's partial update: a request may send any subset of fields, and what it leaves out stays as it is. OfficeChanges has the same properties as OfficeDetails, all nullable and defaulting to null, where null means "not sent". That is unambiguous because the original rules had no nullable, so a null was never a valid value for any field.

PHP
<?php declare(strict_types=1); namespace App\Offices\Office; final readonly class OfficeChanges { /** * @param list<int>|null $tagIds */ public function __construct( public ?string $title = null, public ?string $description = null, public ?string $lat = null, public ?string $lng = null, public ?string $addressLine1 = null, public ?string $addressLine2 = null, public ?int $pricePerDay = null, public ?int $monthlyDiscount = null, public ?bool $hidden = null, public ?int $featuredImageId = null, public ?array $tagIds = null, ) { } }

The Office model

PHP
<?php declare(strict_types=1); namespace App\Offices\Office; use App\Offices\Tag\Tag; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\SoftDeletes; /** * @use HasFactory<OfficeFactory> */ final class Office extends Model { use HasFactory; use SoftDeletes; public const MINIMUM_PRICE_PER_DAY = 100; public const MINIMUM_MONTHLY_DISCOUNT = 0; public const MAXIMUM_MONTHLY_DISCOUNT = 90; private const APPROVAL_TRIGGERS = ['lat', 'lng', 'price_per_day']; public static function submit(int $hostUserId, OfficeDetails $details): self { $office = new self(); $office->user_id = $hostUserId; $office->approval_status = OfficeApprovalStatus::PENDING; $office->applyDetails($details); $office->save(); $office->retag($details->tagIds); return $office; } public static function findByIdForHostOrFail(int $id, int $hostUserId): self { $office = self::query()->findOrFail($id); if ($office->user_id !== $hostUserId) { throw OfficeAccessDeniedException::forOffice($id); } return $office; } public function revise(OfficeChanges $changes): bool { $this->applyChanges($changes); $requiresApproval = $this->isDirty(self::APPROVAL_TRIGGERS); if ($requiresApproval) { $this->approval_status = OfficeApprovalStatus::PENDING; } $this->save(); if ($changes->tagIds !== null) { $this->retag($changes->tagIds); } return $requiresApproval; } /** * @param list<int> $tagIds */ public function retag(array $tagIds): void { $this->tags()->sync($tagIds); } public function tags(): BelongsToMany { return $this->belongsToMany(Tag::class, 'offices_tags'); } // Methods used by other slices, such as images(), remove(), and scopeNearestTo(), are omitted. protected static function newFactory(): OfficeFactory { return OfficeFactory::new(); } /** * @return array<string, string> */ protected function casts(): array { return [ 'user_id' => 'integer', 'featured_image_id' => 'integer', 'lat' => 'decimal:8', 'lng' => 'decimal:8', 'approval_status' => OfficeApprovalStatus::class, 'hidden' => 'boolean', 'price_per_day' => 'integer', 'monthly_discount' => 'integer', ]; } private function applyChanges(OfficeChanges $changes): void { $this->title = $changes->title ?? $this->title; $this->description = $changes->description ?? $this->description; $this->lat = $changes->lat ?? $this->lat; $this->lng = $changes->lng ?? $this->lng; $this->address_line1 = $changes->addressLine1 ?? $this->address_line1; $this->address_line2 = $changes->addressLine2 ?? $this->address_line2; $this->price_per_day = $changes->pricePerDay ?? $this->price_per_day; $this->monthly_discount = $changes->monthlyDiscount ?? $this->monthly_discount; $this->hidden = $changes->hidden ?? $this->hidden; $this->featured_image_id = $changes->featuredImageId ?? $this->featured_image_id; } private function applyDetails(OfficeDetails $details): void { $this->title = $details->title; $this->description = $details->description; $this->lat = $details->lat; $this->lng = $details->lng; $this->address_line1 = $details->addressLine1; $this->address_line2 = $details->addressLine2; $this->price_per_day = $details->pricePerDay; $this->monthly_discount = $details->monthlyDiscount; $this->hidden = $details->hidden; $this->featured_image_id = $details->featuredImageId; } }

Three things moved in from the controller. submit() owns the initial status and the host id, the array assignments at OfficeController.php:74-75. revise() applies only the fields the client sent, owns the isDirty rule from line 108, and returns the decision as a boolean, because telling the admins is a side effect the handler dispatches and a model never dispatches events. findByIdForHostOrFail() replaces route-model binding plus OfficePolicy::update(), so there is no way to get an office for revision without proving you own it. The decimal:8 cast makes isDirty compare coordinates as numbers, so a client that resends 41.996462 for a stored 41.99646200 does not trigger a re-approval. OfficeFactory sits next to the model. The user_id cast to integer matters because the ownership check uses !==.

The ownership failure is an OfficeAccessDeniedException, with the message "You do not own office 7." and the status Response::HTTP_FORBIDDEN. It extends an abstract OfficesException whose render() returns {"message": "..."} with its status, Response::HTTP_UNPROCESSABLE_ENTITY by default, so no controller builds an error response.

The user() and reservations() relations are gone, and user_id is a plain column. Offices never imports a User, and reservations are Reservations' business. There is no $fillable, because Model::unguard() is already global in ergodnc at app/Providers/AppServiceProvider.php:31 and the Form Requests filter the input.

Submitting: command and handler

SubmitOfficeCommand is a readonly object with hostUserId and details. The handler opens the transaction, asks the model to submit itself, and announces the fact.

PHP
<?php declare(strict_types=1); namespace App\Offices\SubmitOffice; use App\Offices\Office\Office; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Database\ConnectionInterface; final readonly class SubmitOfficeCommandHandler { public function __construct( private ConnectionInterface $connection, private Dispatcher $events, ) { } public function handle(SubmitOfficeCommand $command): SubmitOfficeResult { $office = $this->connection->transaction( fn (): Office => Office::submit($command->hostUserId, $command->details), ); $this->events->dispatch(new OfficeSubmittedForApproval($office->id)); return new SubmitOfficeResult($office->load('tags')); } }

The handler does not know what an approval status is, and it does not know that admins exist. SubmitOfficeResult is a readonly DTO whose one property, office, is the model the handler created. The handler loads the tags before returning it, so nothing lazy-loads once the rebuild turns on Model::shouldBeStrict(), which the original does not (it only calls unguard(), at AppServiceProvider.php:31). OfficeSubmittedForApproval is a readonly event carrying one officeId.

Revising: command and handler

ReviseOfficeCommand is a readonly object with officeId, hostUserId, and changes.

PHP
<?php declare(strict_types=1); namespace App\Offices\ReviseOffice; use App\Offices\Office\Office; use App\Offices\SubmitOffice\OfficeSubmittedForApproval; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Database\ConnectionInterface; final readonly class ReviseOfficeCommandHandler { public function __construct( private ConnectionInterface $connection, private Dispatcher $events, ) { } public function handle(ReviseOfficeCommand $command): void { $office = Office::findByIdForHostOrFail($command->officeId, $command->hostUserId); $requiresApproval = $this->connection->transaction( fn (): bool => $office->revise($command->changes), ); if ($requiresApproval) { $this->events->dispatch(new OfficeSubmittedForApproval($office->id)); } } }

The if branches on a decision the model already made, not on model state, so the handler reacts and decides nothing. To the admins a revision that moves the pin or changes the price is a resubmission, so it reuses the event from the submit slice. Both slices live in the same module, so the import is allowed. The handler returns nothing because the endpoint answers 204.

Telling the admins

Offices has to tell the admins, and admins are users, which Identity owns. So Offices defines what it needs:

PHP
<?php declare(strict_types=1); namespace App\Offices\Contracts; interface OfficeAdmins { /** * @return list<string> */ public function emailAddresses(): array; }

App\Identity\Integrations\AdminsForOffices implements it with a query on Identity's own User model (is_admin = true) and is bound in IdentityServiceProvider. The addresses are read when the mail is about to go out, so nothing is copied into an Offices table and nothing can go stale. When admins move to a role table, that one class changes.

The admin query that appeared at OfficeController.php:89 and again at :121 now exists once, behind the contract. The listener sends one on-demand notification per address, so each admin gets their own mail and never sees the others' addresses:

PHP
<?php declare(strict_types=1); namespace App\Offices\SubmitOffice; use App\Offices\Contracts\OfficeAdmins; use Illuminate\Contracts\Notifications\Dispatcher; use Illuminate\Notifications\AnonymousNotifiable; final readonly class NotifyAdminsOfPendingOfficeListener { public function __construct( private OfficeAdmins $admins, private Dispatcher $notifications, ) { } public function handle(OfficeSubmittedForApproval $event): void { foreach ($this->admins->emailAddresses() as $emailAddress) { $admin = (new AnonymousNotifiable())->route('mail', $emailAddress); $this->notifications->send($admin, new OfficePendingApproval($event->officeId)); } } }

OfficePendingApproval replaces the original of the same name. It takes the office id instead of the model, so the queued payload stays small and the mail describes the office as it is when sent, and it has a real subject and body:

PHP
<?php declare(strict_types=1); namespace App\Offices\SubmitOffice; use App\Offices\Office\Office; 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 OfficePendingApproval extends Notification implements ShouldQueue { use Queueable; private const MAX_ATTEMPTS = 3; private const BACKOFF_SECONDS = 60; public int $tries = self::MAX_ATTEMPTS; public int $backoff = self::BACKOFF_SECONDS; public function __construct( public readonly int $officeId, ) { $this->onQueue(QueueName::NOTIFICATIONS->value); } /** * @return list<string> */ public function via(object $notifiable): array { return ['mail']; } public function toMail(object $notifiable): MailMessage { $office = Office::query()->findOrFail($this->officeId); return (new MailMessage()) ->subject("Office \"{$office->title}\" is waiting for approval") ->line("A host submitted \"{$office->title}\" for review.") ->line('The office stays pending until an admin approves it.'); } }

It implements ShouldQueue, sets the notifications queue in the constructor, and declares $tries and $backoff because it talks to a mail server.

Form Requests

ReviseOfficeRequest keeps the original rules: the six required fields get sometimes, so they are validated only when sent. The limits are the constants on Office (MINIMUM_PRICE_PER_DAY 100, MINIMUM_MONTHLY_DISCOUNT 0, MAXIMUM_MONTHLY_DISCOUNT 90), so the model and the request cannot disagree. SubmitOfficeRequest has the same rules without sometimes and without featured_image_id, and its details() passes null for the image. The Rule::when($office->exists, ...) toggle is gone because each request knows which endpoint it serves.

PHP
<?php declare(strict_types=1); namespace App\Offices\ReviseOffice; use App\Offices\Office\Office; use App\Offices\Office\OfficeChanges; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; final class ReviseOfficeRequest extends FormRequest { public function authorize(): bool { return true; } /** * @return array<string, list<mixed>> */ public function rules(): array { return [ 'title' => ['sometimes', 'required', 'string'], 'description' => ['sometimes', 'required', 'string'], 'lat' => ['sometimes', 'required', 'numeric'], 'lng' => ['sometimes', 'required', 'numeric'], 'address_line1' => ['sometimes', 'required', 'string'], 'address_line2' => ['string'], 'price_per_day' => ['sometimes', 'required', 'integer', 'min:'.Office::MINIMUM_PRICE_PER_DAY], 'monthly_discount' => ['integer', 'min:'.Office::MINIMUM_MONTHLY_DISCOUNT, 'max:'.Office::MAXIMUM_MONTHLY_DISCOUNT], 'hidden' => ['boolean'], 'featured_image_id' => [ 'integer', Rule::exists('images', 'id') ->where('resource_type', 'office') ->where('resource_id', $this->officeId()), ], 'tags' => ['array'], 'tags.*' => ['integer', Rule::exists('tags', 'id')], ]; } public function officeId(): int { return (int) $this->route('officeId'); } public function changes(): OfficeChanges { return new OfficeChanges( title: $this->has('title') ? $this->string('title')->toString() : null, description: $this->has('description') ? $this->string('description')->toString() : null, lat: $this->has('lat') ? $this->string('lat')->toString() : null, lng: $this->has('lng') ? $this->string('lng')->toString() : null, addressLine1: $this->has('address_line1') ? $this->string('address_line1')->toString() : null, addressLine2: $this->has('address_line2') ? $this->string('address_line2')->toString() : null, pricePerDay: $this->has('price_per_day') ? $this->integer('price_per_day') : null, monthlyDiscount: $this->has('monthly_discount') ? $this->integer('monthly_discount') : null, hidden: $this->has('hidden') ? $this->boolean('hidden') : null, featuredImageId: $this->has('featured_image_id') ? $this->integer('featured_image_id') : null, tagIds: $this->has('tags') ? array_map(intval(...), $this->array('tags')) : null, ); } }

authorize() returns true on purpose. Authentication is route middleware and ownership is the model lookup, so the request has no third job. has() reads "sent" because a null never passes validation. The featured_image_id rule keeps the intent of OfficeValidator.php:23, an image that belongs to this office, scoped to the office id from the URL. The original passed the bound office there on update, so this changes nothing for revise.

Controllers and resource

PHP
<?php declare(strict_types=1); namespace App\Offices\SubmitOffice; 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('Offices')] final readonly class SubmitOfficeController { public function __construct( private Dispatcher $bus, ) { } #[Endpoint('Submit an office', 'Lists a new office for the authenticated host. It stays pending until an admin approves it.')] #[Authenticated] #[Response( content: [ 'data' => [ 'id' => 7, 'host_user_id' => 3, 'title' => 'Corner office', 'description' => 'Quiet, two windows, near the station.', 'lat' => '41.99646200', 'lng' => '21.43141400', 'address_line1' => '12 Partizanski Odredi', 'address_line2' => null, 'approval_status' => 'pending', 'hidden' => false, 'price_per_day' => 2000, 'monthly_discount' => 10, 'images' => [], 'reservations_count' => 0, 'tags' => [ ['id' => 1, 'name' => 'Parking'], ], ], ], status: SymfonyResponse::HTTP_CREATED, )] public function __invoke(SubmitOfficeRequest $request): JsonResponse { $result = $this->bus->dispatch(new SubmitOfficeCommand( hostUserId: $request->user()->id, details: $request->details(), )); return SubmitOfficeResource::make($result) ->response() ->setStatusCode(SymfonyResponse::HTTP_CREATED); } }
PHP
<?php declare(strict_types=1); namespace App\Offices\ReviseOffice; 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 Knuckles\Scribe\Attributes\UrlParam; use Symfony\Component\HttpFoundation\Response as SymfonyResponse; #[Group('Offices')] final readonly class ReviseOfficeController { public function __construct( private Dispatcher $bus, ) { } #[Endpoint('Revise an office', 'Updates the fields sent for an office owned by the authenticated host. Fields left out stay as they are. A change to the location or the daily price sends it back to pending approval.')] #[Authenticated] #[UrlParam('officeId', 'integer', 'The id of the office to revise.', example: 7)] #[Response(status: SymfonyResponse::HTTP_NO_CONTENT)] public function __invoke(ReviseOfficeRequest $request): JsonResponse { $this->bus->dispatch(new ReviseOfficeCommand( officeId: $request->officeId(), hostUserId: $request->user()->id, changes: $request->changes(), )); return new JsonResponse(null, SymfonyResponse::HTTP_NO_CONTENT); } }

The host id comes from $request->user(), never from the body, and the controller reads it through the auth guard, so it imports no User class. Both statuses are explicit, and the #[Response] example in the submit controller has the same keys as the resource.

SubmitOfficeResource is a plain JsonResource over SubmitOfficeResult and reads the office through it. Its toArray() names these keys: id, host_user_id, title, description, lat, lng, address_line1, address_line2, approval_status (the enum's string value), hidden, price_per_day, monthly_discount, images, reservations_count, and tags. A new office has no images and no reservations, so the resource sets images to an empty list and reservations_count to 0 itself. tags is TagResource::collection() over the office's Tag models, shown as {id, name}, and is included only when the relation is loaded. Every key is listed, so the response shape is readable from one file, unlike OfficeResource.php:25-28, which subtracts four keys from the model's array.

Abilities, routes, and wiring

OfficeAbility holds CREATE = 'office.create' and UPDATE = 'office.update'. The strings stay because existing tokens carry them. The routes check them with middleware instead of tokenCan() in the method body, and each route gets a name:

PHP
<?php declare(strict_types=1); use App\Offices\OfficeAbility; use App\Offices\ReviseOffice\ReviseOfficeController; use App\Offices\SubmitOffice\SubmitOfficeController; use Illuminate\Support\Facades\Route; // Routes from the other slices in this module are omitted. Route::post('/offices', SubmitOfficeController::class) ->middleware(['auth:sanctum', 'verified', 'abilities:'.OfficeAbility::CREATE]) ->name('offices.offices.submit'); Route::put('/offices/{officeId}', ReviseOfficeController::class) ->middleware(['auth:sanctum', 'verified', 'abilities:'.OfficeAbility::UPDATE]) ->whereNumber('officeId') ->name('offices.offices.revise');

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.

OfficesServiceProvider maps both commands to their handlers with Bus::map(), so a reader can open one file and see every write the module supports. It registers the listener for OfficeSubmittedForApproval and loads offices-routes.php inside the api middleware group. The module providers are registered in bootstrap/providers.php. Facades are fine in providers, route files, and migrations. Production classes get their dependencies injected.

PHP
<?php declare(strict_types=1); namespace App\Offices; use App\Offices\ReviseOffice\ReviseOfficeCommand; use App\Offices\ReviseOffice\ReviseOfficeCommandHandler; use App\Offices\SubmitOffice\NotifyAdminsOfPendingOfficeListener; use App\Offices\SubmitOffice\OfficeSubmittedForApproval; use App\Offices\SubmitOffice\SubmitOfficeCommand; use App\Offices\SubmitOffice\SubmitOfficeCommandHandler; use Illuminate\Support\Facades\Bus; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Route; use Illuminate\Support\ServiceProvider; final class OfficesServiceProvider extends ServiceProvider { // Entries for the other slices in this module are omitted. public function boot(): void { Bus::map([ SubmitOfficeCommand::class => SubmitOfficeCommandHandler::class, ReviseOfficeCommand::class => ReviseOfficeCommandHandler::class, ]); Event::listen(OfficeSubmittedForApproval::class, NotifyAdminsOfPendingOfficeListener::class); Route::middleware('api')->group(__DIR__.'/offices-routes.php'); } }

What changed in the API contract

  • PUT /offices/{id} returns 204 with no body. It returned 200 with the full office.

  • hidden is accepted as a boolean on both endpoints. The original validated it with a bool rule that Laravel 8 does not implement (it has boolean), so any request that sent hidden failed with a 500.

  • featured_image_id is accepted on revise only. POST /offices ignores it, where the original answered 422 for any value because no image can belong to an office that does not exist yet.

  • POST /offices still returns 201, now set explicitly. The nested user object is replaced by host_user_id, which also drops the is_admin flag the original exposed for the host. Tags are {"id", "name"} without the pivot object, and images stays as an empty list. user_id, created_at, updated_at, and deleted_at stay out. Fields the client did not send, such as monthly_discount and address_line2, were missing from the original response because the model is not refreshed after the insert; they are always present now.

  • approval_status is "pending" or "approved" instead of 1 or 2.

  • A token without the office.create or office.update ability still gets a 403, now with the message "Invalid ability provided." from Sanctum's middleware, before validation runs.

  • A revision by someone who is not the host returns 403 with {"message": "You do not own office 7."} instead of "This action is unauthorized."

  • A non-host who sends an invalid payload gets 422, not 403, because the Form Request validates before the handler checks ownership.

  • A non-existent id on PUT returns 404 with {"message": "No query results for model [App\\Offices\\Office\\Office] 7"}, now after the ability check and validation. The original answered 404 during route binding, before either.

  • PUT /offices/abc returns 404 "The route offices/abc could not be found." from the router (whereNumber) instead of "No query results for model [App\Models\Office] abc".

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 integer approval_status and the nested user object (OfficeControllerTest.php:246-248), so both need work before this ships. More will come up once the code is in use. What matters is that validation lives in two Form Requests, the re-approval rule lives on the Office model, and the admin lookup sits behind OfficeAdmins, so a change to any of them touches one class.