Lesson 12 of 22 · Architecture and Code Organization
Laravel Resource Controllers That Never Get Split
ReservationController was created with php artisan make:controller ReservationController --resource, and it has grown the way resource controllers grow. Five public methods, a constructor that injects what any of them might need, and one update() that decides what it is doing by looking at which fields arrived. Here it is after the previous lessons, with store() already thin.
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Http\Resources\ReservationResource;
use App\Models\Reservation;
use App\Pricing\NightlyRatePricing;
use App\Services\RequestReservation;
use Carbon\CarbonImmutable;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
class ReservationController extends Controller
{
public function __construct(
private readonly RequestReservation $requestReservation,
private readonly NightlyRatePricing $pricing,
) {
}
public function index(Request $request): AnonymousResourceCollection
{
$reservations = Reservation::query()
->with(['guest:id,name', 'room:id,number'])
->when($request->input('status'), fn ($query, $status) => $query->where('status', $status))
->orderBy($request->input('sort', 'check_in'))
->paginate(25);
return ReservationResource::collection($reservations);
}
public function show(int $id): ReservationResource
{
$reservation = Reservation::query()
->with(['guest', 'room.roomType'])
->findOrFail($id);
return new ReservationResource($reservation);
}
public function store(Request $request): JsonResponse
{
$attributes = $request->validate([
'room_id' => 'required|exists:rooms,id',
'check_in' => 'required|date|after_or_equal:today',
'check_out' => 'required|date|after:check_in',
'adults' => 'required|integer|min:1',
'children' => 'required|integer|min:0',
]);
$reservation = $this->requestReservation->handle(
guestId: (int) $request->user()->guest_id,
attributes: $attributes,
);
return (new ReservationResource($reservation))->response()->setStatusCode(201);
}
public function update(Request $request, int $id): JsonResponse
{
$attributes = $request->validate([
'check_in' => 'sometimes|date',
'check_out' => 'sometimes|date|after:check_in',
'status' => 'sometimes|in:cancelled,checked_in',
]);
$reservation = Reservation::query()->with('room.roomType')->findOrFail($id);
if (isset($attributes['check_in'], $attributes['check_out'])) {
$reservation->check_in = CarbonImmutable::parse($attributes['check_in']);
$reservation->check_out = CarbonImmutable::parse($attributes['check_out']);
$reservation->total_cents = $this->pricing->totalCents(
$reservation->room->roomType,
$reservation->check_in,
$reservation->check_out,
);
}
if (($attributes['status'] ?? null) === 'cancelled') {
$reservation->status = 'cancelled';
}
if (($attributes['status'] ?? null) === 'checked_in') {
$reservation->status = 'checked_in';
}
$reservation->save();
return new JsonResponse(null, 204);
}
public function destroy(int $id): JsonResponse
{
$reservation = Reservation::query()->findOrFail($id);
$reservation->status = 'cancelled';
$reservation->save();
return new JsonResponse(null, 204);
}
}The front end has been a single-page app for a while, so these methods answer with JSON, and the redirect that store() used to return was the last leftover from the Blade form. create() and edit(), which rendered the forms, went with it. The other change is that RequestReservation moved from a store() parameter into the constructor, and NightlyRatePricing joined it for update(), because the model no longer prices itself.
What one file costs
Nobody decided this file should hold five unrelated actions. Laravel handed over one controller per resource, and every change to reservations landed in it because that is where reservations live.
The constructor is the first cost. It injects RequestReservation for store() and NightlyRatePricing for update(). Every request to index() builds both, and reading the top of the file tells you what any action might need, not what the one you are looking at needs.
The shared surface is the second. Listing, showing, requesting, changing, and cancelling a reservation have nothing in common except the word in their name, but they share imports, a constructor, and any private helper someone adds. Two developers changing two features edit the same file and can collide in version control.
The third cost is that update() is three features wearing one method. Changing dates, cancelling, and checking in are different actions with different rules, and the method finds out which one it is running by inspecting the payload. That gets its own lesson in the next chapter. For now it just moves.
One class per action
A single-action controller is a class with one public __invoke() method, registered as a route by class name. Each one declares only what it needs.
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Reservations;
use App\Http\Requests\ReservationRequest;
use App\Http\Resources\ReservationResource;
use App\Services\RequestReservation;
use Illuminate\Http\JsonResponse;
final readonly class RequestReservationController
{
public function __construct(
private RequestReservation $requestReservation,
) {
}
public function __invoke(ReservationRequest $request): JsonResponse
{
$reservation = $this->requestReservation->handle(
guestId: (int) $request->user()->guest_id,
attributes: $request->validated(),
);
return (new ReservationResource($reservation))->response()->setStatusCode(201);
}
}<?php
declare(strict_types=1);
namespace App\Http\Controllers\Reservations;
use App\Models\Reservation;
use Illuminate\Http\JsonResponse;
final readonly class CancelReservationController
{
public function __invoke(int $id): JsonResponse
{
$reservation = Reservation::query()->findOrFail($id);
$reservation->status = 'cancelled';
$reservation->save();
return new JsonResponse(null, 204);
}
}Two things changed in shape. The classes are final readonly and do not extend the application's base Controller. PHP does not allow a readonly class to extend a non-readonly parent, and a single-action controller needs nothing from that parent: middleware is attached in the route file, and validation comes from a Form Request. The second change is that inline $request->validate() moved into App\Http\Requests\ReservationRequest, written with array-syntax rules, and shared by RequestReservationController and ChangeReservationController, because both accept dates.
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
final class ReservationRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
/**
* @return array<string, list<string>>
*/
public function rules(): array
{
$creating = $this->isMethod('post');
return [
'room_id' => [$creating ? 'required' : 'sometimes', 'integer', 'exists:rooms,id'],
'check_in' => [$creating ? 'required' : 'sometimes', 'date_format:Y-m-d', 'after_or_equal:today'],
'check_out' => [$creating ? 'required' : 'sometimes', 'date_format:Y-m-d', 'after:check_in'],
'adults' => [$creating ? 'required' : 'sometimes', 'integer', 'min:1'],
'children' => ['sometimes', 'integer', 'min:0'],
'status' => ['sometimes', 'in:cancelled,checked_in'],
];
}
}The class asks which HTTP method it is running under, because a create needs room_id and a date change does not, and status is there only for the PATCH. That compromise is the kind of thing a shared request class forces, and a later lesson splits it.
The route file, routes/api.php, names each class directly, so the wiring reads as a list of what the application can do.
<?php
declare(strict_types=1);
use App\Http\Controllers\ChannelImportController;
use App\Http\Controllers\Reservations\CancelReservationController;
use App\Http\Controllers\Reservations\ChangeReservationController;
use App\Http\Controllers\Reservations\ListReservationsController;
use App\Http\Controllers\Reservations\RequestReservationController;
use App\Http\Controllers\Reservations\ShowReservationController;
use Illuminate\Support\Facades\Route;
Route::middleware('auth:sanctum')->group(function (): void {
Route::get('/reservations', ListReservationsController::class)->name('reservations.list');
Route::post('/reservations', RequestReservationController::class)->name('reservations.request');
Route::get('/reservations/{id}', ShowReservationController::class)->name('reservations.show');
Route::patch('/reservations/{id}', ChangeReservationController::class)->name('reservations.change');
Route::post('/reservations/{id}/cancel', CancelReservationController::class)->name('reservations.cancel');
Route::post('/reservations/import', ChannelImportController::class)->name('reservations.import');
});destroy() became CancelReservationController on a POST .../cancel route rather than a DELETE. A cancelled reservation keeps its row, its payments, and its history, and the route now says what happens.
ListReservationsController and ShowReservationController hold the bodies of index() and show() unchanged. ChangeReservationController holds update() unchanged except that it takes ReservationRequest and keeps NightlyRatePricing in its constructor. It still decides at runtime which of three things it is doing. The shared rules also tighten the PATCH date validation: check_in now needs date_format:Y-m-d and after_or_equal:today where the inline rules accepted any date. And children loses required on create, while handle() still reads $attributes['children'], so a form that omits it now fails with an ErrorException for the undefined key. A later lesson comes back to that rule.
This is a split, not a redesign. The models still sit in app/Models, the use case class in app/Services, the controllers in app/Http/Controllers/Reservations, the request in app/Http/Requests, the resource in app/Http/Resources, the mailable in app/Mail, and the pricing in app/Pricing. To read the "request a reservation" feature end to end you open seven folders. The next lesson is about that. ChannelImportController stays in app/Http/Controllers as it is for now.
The one thing to remember
A file grows because nothing stops it, and every action in a shared controller pays for every other action's dependencies and edits. One class per action, with one __invoke() and its own constructor, makes each file say exactly what one endpoint needs.