Refactoring Ergodnc - Turning Validation Errors Into Domain Exceptions
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 two of its endpoints: DELETE /offices/{office} and DELETE /offices/{office}/images/{image}. It covers what is wrong with them and a rebuild as two vertical slices where every business rule is a domain exception that renders itself.
Ergodnc runs Laravel 8. The rebuild targets Laravel 13.
What the endpoints do today
The routes are routes/api.php:32 and :36, both behind auth:sanctum and verified. Deleting an office is delete at app/Http/Controllers/OfficeController.php:129-149:
<?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(), create(), and update() omitted
public function delete(Office $office)
{
abort_unless(auth()->user()->tokenCan('office.delete'),
Response::HTTP_FORBIDDEN
);
$this->authorize('delete', $office);
throw_if(
$office->reservations()->where('status', Reservation::STATUS_ACTIVE)->exists(),
ValidationException::withMessages(['office' => 'Cannot delete this office!'])
);
$office->images()->each(function ($image) {
Storage::delete($image->path);
$image->delete();
});
$office->delete();
}
}Deleting an image is delete at app/Http/Controllers/OfficeImageController.php:37-56:
<?php
namespace App\Http\Controllers;
use App\Http\Resources\ImageResource;
use App\Models\Image;
use App\Models\Office;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
class OfficeImageController extends Controller
{
// store() omitted
public function delete(Office $office, Image $image)
{
abort_unless(auth()->user()->tokenCan('office.update'),
Response::HTTP_FORBIDDEN
);
$this->authorize('update', $office);
throw_if($office->images()->count() == 1,
ValidationException::withMessages(['image' => 'Cannot delete the only image.'])
);
throw_if($office->featured_image_id == $image->id,
ValidationException::withMessages(['image' => 'Cannot delete the featured image.'])
);
Storage::delete($image->path);
$image->delete();
}
}Ownership is app/Policies/OfficePolicy.php:13-21: update() and delete() both compare $user->id == $office->user_id. The office endpoint uses delete(), the image endpoint uses update().
What is wrong with it
There are no slices and no commands. Two endpoints are spread across two controllers with several actions each, and everything they touch sits in Laravel's type folders:
app/Http/Controllers,app/Models,app/Policies,app/Http/Resources.Both routes use route-model binding (
routes/api.php:32and:36). The lookup is hidden, and the rule "an image belongs to the office in the URL" is enforced only because{image:id}makes Laravel scope the image through the office's relation. Nothing in the controller says so.Ownership is fetch, then check. Binding loads the office by id and the policy compares ids afterwards (
OfficeController.php:135,OfficeImageController.php:43,OfficePolicy.php:13-21).The token abilities are string literals checked inline with
abort_unless(OfficeController.php:131,OfficeImageController.php:39), so each controller builds its own 403.Three business rules are thrown as
ValidationException(OfficeController.php:137-140,OfficeImageController.php:45-51). A client sees a 422 with anerrors.officeorerrors.imagekey for a request whose input was valid.The controllers decide what the data allows. They count images, compare
featured_image_id, and ask for active reservations (OfficeImageController.php:45and:49,OfficeController.php:138). None of that lives on the model that owns the data.Officeholds aHasManyto reservations (Office.php:35-38) and the delete endpoint walks it, with the int constantReservation::STATUS_ACTIVE(OfficeController.php:138). Offices and reservations are separate capabilities, and the relation fuses them.Both controllers call the
Storagefacade (OfficeController.php:143,OfficeImageController.php:53). The office delete removes each file and row inside a loop with no transaction (OfficeController.php:142-146), so a failure halfway leaves an office with some of its images gone.The controllers delete rows themselves instead of calling a domain method (
OfficeController.php:145and:148,OfficeImageController.php:55).File deletion runs synchronously inside the request (
OfficeController.php:143,OfficeImageController.php:53).Both deletes return nothing, so they answer 200 with an empty body.
auth()andStorageresolve their dependencies from the container globally, so the classes hide what they need.Neither change announces itself with an event.
Neither route has a name.
The refactor
The rebuild splits the app into modules: App\Reservations, App\Offices, and App\Identity, which owns the User model, login, and tokens. Each endpoint becomes a vertical slice in App\Offices\, and the Office model, its factory, and the four exceptions sit together in App\Offices\Office\.
Before, at commit 42907c0:
app/
Http/
Kernel.php
Controllers/
OfficeController.php
OfficeImageController.php
Models/
Image.php
Office.php
Reservation.php
Policies/
OfficePolicy.php
Providers/
AppServiceProvider.php
database/
factories/
OfficeFactory.php
routes/
api.phpAfter the rebuild:
app/
Identity/
IdentityServiceProvider.php
User/
User.php
Offices/
OfficeAbility.php
OfficesException.php
OfficesServiceProvider.php
offices-routes.php
Contracts/
ActiveReservations.php
OfficeReservations.php
DeleteOffice/
DeleteOfficeCommand.php
DeleteOfficeCommandHandler.php
DeleteOfficeController.php
DeleteOfficeFilesListener.php
OfficeDeleted.php
DeleteOfficeImage/
DeleteOfficeImageCommand.php
DeleteOfficeImageCommandHandler.php
DeleteOfficeImageController.php
DeleteOfficeImageFileListener.php
OfficeImageDeleted.php
Files/
OfficeImageFiles.php
Image/
Image.php
Office/
CannotDeleteFeaturedImageException.php
CannotDeleteOnlyImageException.php
Office.php
OfficeAccessDeniedException.php
OfficeFactory.php
OfficeHasActiveReservationsException.php
Reservations/
ReservationsServiceProvider.php
Integrations/
ReservationsForOffices.php
Reservation/
Reservation.php
ReservationStatus.php
Shared/
Queue/
QueueName.php
bootstrap/
app.php
providers.phpApp\Offices\Contracts\ holds the contract Offices needs from Reservations, and App\Offices\Files\ holds the file handling. Identity\User\User and Reservation appear because the rebuild touches them: the morph map needs the user, and the reservations check reads the reservation status. IdentityServiceProvider and ReservationsServiceProvider are the providers of the other two modules, and bootstrap/providers.php registers all three.
The Office model owns the rules
Every rule from the original controllers moves onto Office: who may touch it, which images may go, and when the whole office may go.
<?php
declare(strict_types=1);
namespace App\Offices\Office;
use App\Offices\Contracts\ActiveReservations;
use App\Offices\Image\Image;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* @use HasFactory<OfficeFactory>
*/
final class Office extends Model
{
use HasFactory;
use SoftDeletes;
private const LAST_IMAGE_COUNT = 1;
// Methods used by other slices, such as submit() and revise(), are omitted.
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 removeImage(int $imageId): string
{
$image = $this->images()->findOrFail($imageId);
if ($this->images()->count() === self::LAST_IMAGE_COUNT) {
throw new CannotDeleteOnlyImageException();
}
if ($this->featured_image_id === $image->id) {
throw new CannotDeleteFeaturedImageException();
}
$image->delete();
return $image->path;
}
/**
* @return list<string> the paths of the deleted images
*/
public function remove(ActiveReservations $reservations): array
{
if ($reservations->existFor($this->id)) {
throw new OfficeHasActiveReservationsException();
}
$paths = $this->images()->pluck('path')->all();
$this->images()->delete();
$this->delete();
return $paths;
}
public function images(): MorphMany
{
return $this->morphMany(Image::class, 'resource');
}
protected static function newFactory(): OfficeFactory
{
return OfficeFactory::new();
}
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'user_id' => 'integer',
'featured_image_id' => 'integer',
// Casts used by other slices are omitted.
];
}
}findByIdForHostOrFail() replaces route-model binding plus the policy. The ownership gate sits inside the lookup, so no code path reaches an office without passing it, and the user_id !== $hostUserId comparison is strict because the cast makes both sides ints.
removeImage() keeps the original order of checks: the image must belong to this office, it must not be the only one, it must not be the featured one. findOrFail() on the relation replaces the route scoping from {image:id}, so "image 12 does not belong to office 7" is a plain 404 that the model states in code. A missing image needs no custom exception, because Laravel's ModelNotFoundException already becomes the 404.
remove() deletes the images with one query and soft-deletes the office like the original. It returns the stored paths because the model decides what is deleted, and what happens to the files on disk is not its concern. Image is a final Eloquent model with the resource morph the original had. The original registers the morph map in AppServiceProvider.php:33-36; the rebuild moves office into OfficesServiceProvider and user into IdentityServiceProvider, both through Relation::enforceMorphMap(), which merges with earlier entries by default. Without the user entry Sanctum's token relation on the user would throw once the map is enforced. The stored resource_type value office keeps resolving.
The exceptions
OfficesException is the abstract base. It renders {"message": "..."} with its status, and controllers never catch anything:
<?php
declare(strict_types=1);
namespace App\Offices;
use Illuminate\Http\JsonResponse;
use RuntimeException;
use Symfony\Component\HttpFoundation\Response;
abstract class OfficesException extends RuntimeException
{
protected int $status = Response::HTTP_UNPROCESSABLE_ENTITY;
public function render(): JsonResponse
{
return new JsonResponse(['message' => $this->getMessage()], $this->status);
}
}Each concrete exception overrides $status and sets its message. Four cover this flow:
OfficeAccessDeniedException::forOffice(int $officeId)rendersResponse::HTTP_FORBIDDENwith "You do not own office {id}."OfficeHasActiveReservationsExceptionrendersResponse::HTTP_CONFLICTwith "An office with active reservations cannot be deleted."CannotDeleteOnlyImageExceptionrendersResponse::HTTP_CONFLICTwith "Cannot delete the only image."CannotDeleteFeaturedImageExceptionrendersResponse::HTTP_CONFLICTwith "Cannot delete the featured image."
The three rules describe the office's current state, so they render 409 where the original rendered 422 for valid input.
Asking Reservations about active reservations
Offices needs one answer from Reservations: does this office have an active reservation? Offices declares the question in its own namespace:
<?php
declare(strict_types=1);
namespace App\Offices\Contracts;
interface ActiveReservations
{
public function existFor(int $officeId): bool;
}App\Reservations\Integrations\ReservationsForOffices implements it with a query on its own table, and ReservationsServiceProvider binds the interface to it:
<?php
declare(strict_types=1);
namespace App\Reservations\Integrations;
use App\Offices\Contracts\ActiveReservations;
use App\Offices\Contracts\OfficeReservations;
use App\Reservations\Reservation\Reservation;
use App\Reservations\Reservation\ReservationStatus;
final readonly class ReservationsForOffices implements ActiveReservations, OfficeReservations
{
// activeCountsFor() and officeIdsReservedBy(), from OfficeReservations (the office listings), are omitted.
public function existFor(int $officeId): bool
{
return Reservation::query()
->where('office_id', $officeId)
->where('status', ReservationStatus::ACTIVE)
->exists();
}
}I chose a contract over a read-only query on a ConnectionInterface because a raw query would put the table name, the office_id column, and the status string 'active' inside Offices, and the module that owns the meaning of "active" could no longer change it alone. The answer is read at the moment of deletion because it has to be current then, and nothing is copied into an Offices table.
The contract is passed into Office::remove() so the rule stays on the model and the handler needs no if. As in the original, a booking that lands between the check and the delete is not prevented.
Files
The original controllers call Storage directly. The rebuild puts every filesystem call in one class that injects Laravel's filesystem factory contract and uses the default disk, the one the original Storage::delete() used:
<?php
declare(strict_types=1);
namespace App\Offices\Files;
use Illuminate\Contracts\Filesystem\Factory;
final readonly class OfficeImageFiles
{
public function __construct(
private Factory $filesystem,
) {
}
/**
* @param list<string> $paths
*/
public function delete(array $paths): void
{
$this->filesystem->disk()->delete($paths);
}
}Deleting files is a side effect of a fact, so it does not belong in the handler. The handlers dispatch OfficeDeleted and OfficeImageDeleted, and a queued listener removes the files. The response does not wait for the disk or for S3, a failed delete is retried instead of turning an already committed delete into a 500, and the events carry the paths because the rows are gone by the time the listener runs.
<?php
declare(strict_types=1);
namespace App\Offices\DeleteOffice;
use App\Offices\Files\OfficeImageFiles;
use App\Shared\Queue\QueueName;
use Illuminate\Contracts\Queue\ShouldQueue;
final readonly class DeleteOfficeFilesListener implements ShouldQueue
{
private const TRIES = 3;
private const BACKOFF_SECONDS = [10, 60];
public function __construct(
private OfficeImageFiles $files,
) {
}
public function handle(OfficeDeleted $event): void
{
$this->files->delete($event->imagePaths);
}
public function viaQueue(): string
{
return QueueName::FILES->value;
}
public function tries(): int
{
return self::TRIES;
}
/**
* @return list<int>
*/
public function backoff(): array
{
return self::BACKOFF_SECONDS;
}
}OfficeDeleted is a readonly event with officeId and imagePaths (list<string>). The delete-image slice has the same shape: OfficeImageDeleted carries officeId, imageId, and path, and DeleteOfficeImageFileListener deletes that one file. QueueName::FILES = 'files' is a new case on the shared enum, next to NOTIFICATIONS. The listener sets its queue in viaQueue() instead of a constructor, because Laravel 13 reads that method (or a queue attribute) from a queued listener and ignores a $queue property.
Command handlers
DeleteOfficeCommand holds officeId and hostUserId. The host id comes from the authenticated principal, never from the request. The handler has no branch:
<?php
declare(strict_types=1);
namespace App\Offices\DeleteOffice;
use App\Offices\Contracts\ActiveReservations;
use App\Offices\Office\Office;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Database\ConnectionInterface;
final readonly class DeleteOfficeCommandHandler
{
public function __construct(
private ActiveReservations $reservations,
private ConnectionInterface $connection,
private Dispatcher $events,
) {
}
public function handle(DeleteOfficeCommand $command): void
{
$office = Office::findByIdForHostOrFail($command->officeId, $command->hostUserId);
$imagePaths = $this->connection->transaction(
fn (): array => $office->remove($this->reservations),
);
$this->events->dispatch(new OfficeDeleted($office->id, $imagePaths));
}
}The transaction covers the image rows and the soft delete, which the original ran as separate statements. The event is dispatched after the transaction commits, so the listener never deletes files for a rolled-back office. The handler returns nothing because the endpoint has no body to build.
<?php
declare(strict_types=1);
namespace App\Offices\DeleteOfficeImage;
use App\Offices\Office\Office;
use Illuminate\Contracts\Events\Dispatcher;
final readonly class DeleteOfficeImageCommandHandler
{
public function __construct(
private Dispatcher $events,
) {
}
public function handle(DeleteOfficeImageCommand $command): void
{
$office = Office::findByIdForHostOrFail($command->officeId, $command->hostUserId);
$path = $office->removeImage($command->imageId);
$this->events->dispatch(new OfficeImageDeleted($office->id, $command->imageId, $path));
}
}DeleteOfficeImageCommand holds officeId, imageId, and hostUserId.
Controllers
Neither endpoint takes a body, so the slices skip the {Action}Request class. The ids arrive as route parameters, and the host id comes from $request->user(), which reads the auth guard and imports nothing.
<?php
declare(strict_types=1);
namespace App\Offices\DeleteOffice;
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('Offices')]
final readonly class DeleteOfficeController
{
public function __construct(
private Dispatcher $bus,
) {
}
#[Endpoint('Delete an office', 'Deletes an office the authenticated host owns, together with its images.')]
#[Authenticated]
#[UrlParam('officeId', 'integer', 'The id of the office.', example: 7)]
#[Response(status: SymfonyResponse::HTTP_NO_CONTENT)]
public function __invoke(Request $request, int $officeId): JsonResponse
{
$this->bus->dispatch(new DeleteOfficeCommand(
officeId: $officeId,
hostUserId: $request->user()->id,
));
return new JsonResponse(null, SymfonyResponse::HTTP_NO_CONTENT);
}
}DeleteOfficeImageController has the same shape with a second #[UrlParam('imageId', ...)].
Routes and wiring
The ability strings become constants on OfficeAbility (DELETE = 'office.delete', UPDATE = 'office.update'), and the routes check them with middleware instead of abort_unless. The ids are plain route parameters and the routes are named:
<?php
declare(strict_types=1);
use App\Offices\DeleteOffice\DeleteOfficeController;
use App\Offices\DeleteOfficeImage\DeleteOfficeImageController;
use App\Offices\OfficeAbility;
use Illuminate\Support\Facades\Route;
// Routes from the other slices in this module are omitted.
Route::delete('/offices/{officeId}', DeleteOfficeController::class)
->middleware(['auth:sanctum', 'verified', 'abilities:'.OfficeAbility::DELETE])
->whereNumber('officeId')
->name('offices.offices.delete');
Route::delete('/offices/{officeId}/images/{imageId}', DeleteOfficeImageController::class)
->middleware(['auth:sanctum', 'verified', 'abilities:'.OfficeAbility::UPDATE])
->whereNumber(['officeId', 'imageId'])
->name('offices.images.delete');The image route keeps office.update, as the original did, because changing a photo edits the listing and only deleting the office needs office.delete. The abilities alias points at Sanctum's CheckAbilities middleware and is registered in bootstrap/app.php. That file also calls $middleware->throttleApi(), because ergodnc throttles every API route (app/Http/Kernel.php:44) and in Laravel 13 the api group only does that when asked.
OfficesServiceProvider wires the module: the morph map, each command to its handler, each event to its file listener, and the route file inside the api middleware group.
<?php
declare(strict_types=1);
namespace App\Offices;
use App\Offices\DeleteOffice\DeleteOfficeCommand;
use App\Offices\DeleteOffice\DeleteOfficeCommandHandler;
use App\Offices\DeleteOffice\DeleteOfficeFilesListener;
use App\Offices\DeleteOffice\OfficeDeleted;
use App\Offices\DeleteOfficeImage\DeleteOfficeImageCommand;
use App\Offices\DeleteOfficeImage\DeleteOfficeImageCommandHandler;
use App\Offices\DeleteOfficeImage\DeleteOfficeImageFileListener;
use App\Offices\DeleteOfficeImage\OfficeImageDeleted;
use App\Offices\Office\Office;
use Illuminate\Database\Eloquent\Relations\Relation;
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 from the other slices in this module are omitted.
public function boot(): void
{
Relation::enforceMorphMap(['office' => Office::class]);
Bus::map([
DeleteOfficeCommand::class => DeleteOfficeCommandHandler::class,
DeleteOfficeImageCommand::class => DeleteOfficeImageCommandHandler::class,
]);
Event::listen(OfficeDeleted::class, DeleteOfficeFilesListener::class);
Event::listen(OfficeImageDeleted::class, DeleteOfficeImageFileListener::class);
Route::middleware('api')->group(__DIR__.'/offices-routes.php');
}
}ReservationsServiceProvider binds ActiveReservations and OfficeReservations to ReservationsForOffices. Facades are fine in providers, route files, and migrations; production classes get their dependencies injected.
What changed in the API contract
Both deletes return 204 with no body instead of 200 with an empty body.
Deleting an office with active reservations returns 409 with
{"message": "An office with active reservations cannot be deleted."}instead of 422 with{"message": "The given data was invalid.", "errors": {"office": ["Cannot delete this office!"]}}.Deleting the only image returns 409 with
{"message": "Cannot delete the only image."}instead of a 422 validation error keyed onimage.Deleting the featured image returns 409 with
{"message": "Cannot delete the featured image."}instead of a 422 validation error keyed onimage.A non-owner on either endpoint gets 403 with
{"message": "You do not own office N."}instead of the policy's default "This action is unauthorized."A missing office still returns 404, with
{"message": "No query results for model [App\\Offices\\Office\\Office] 7"}instead ofNo query results for model [App\\Models\\Office] 7. An image id that belongs to another office or does not exist still returns 404, with[App\\Offices\\Image\\Image] 12instead of[App\\Models\\Image] 12.A non-owner who sends an image id that is not in that office gets 403 "You do not own office N." where the original answered 404, because the original scoped the image through the route before checking ownership (
routes/api.php:36,OfficeImageController.php:43) and the rebuild checks ownership first.A non-numeric id in either URL returns 404
{"message": "The route offices/abc could not be found."}from the router, even for an unauthenticated caller. The original answered 401 first, or 404 "No query results for model [App\Models\Office] abc".A token without the needed ability still gets a 403, now with the message "Invalid ability provided." from Sanctum's middleware. That check now runs first, so a token without the ability gets 403 where the original answered 404 for a missing office or image.
Image files are removed by a queued listener after the response, so a file can stay readable until the worker runs.
The routes are named
offices.offices.deleteandoffices.images.delete. Paths and verbs are unchanged.
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, the feature tests still expect the old 200 and 422 (OfficeControllerTest.php:421, :444), and the image upload endpoint is not rebuilt. More will come up once the code is in use. What matters is that the delete rules live in Office::remove() and Office::removeImage(), and file deletion happens in queued listeners, so the next rule about deleting an office has one obvious home.