Lesson 16 of 22 · Request Handling and API Design
Laravel Validation Is Not Enough
The write side names its columns now. The read side still takes the client's word for everything. The reservations list is the staff screen: it filters by status and arrival date and sorts by whichever column the frontend asks for. It lives in its own ListReservations/ folder with a Form Request, and this lesson shows that request. The controller's body is the old index() plus an arrival-date filter the front desk asked for.
<?php
declare(strict_types=1);
namespace App\Reservations\ListReservations;
use Illuminate\Foundation\Http\FormRequest;
final class ListReservationsRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
/**
* @return array<string, list<mixed>>
*/
public function rules(): array
{
return [
'sort' => ['sometimes', 'string'],
'status' => ['sometimes', 'string'],
'check_in_from' => ['sometimes', 'date'],
];
}
}<?php
declare(strict_types=1);
namespace App\Reservations\ListReservations;
use App\Reservations\Reservation\Reservation;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
final readonly class ListReservationsController
{
public function __invoke(ListReservationsRequest $request): JsonResponse
{
$reservations = Reservation::query()
->with(['guest:id,name', 'room:id,number'])
->when(
$request->filled('status'),
fn (Builder $query) => $query->where('status', $request->input('status')),
)
->when(
$request->filled('check_in_from'),
fn (Builder $query) => $query->where('check_in', '>=', $request->input('check_in_from')),
)
->orderBy($request->input('sort', 'check_in'))
->paginate(25);
return ListReservationsResource::collection($reservations)->response();
}
}Every rule passes for the requests the frontend sends, because the rules were written by looking at the frontend.
Three inputs, three ways to be wrong
sort is validated as a string. ?sort=guest is a string, so it passes, and orderBy('guest') produces ORDER BY `guest` on MySQL. There is no guest column on reservations, so the database throws and the client gets a 500. ?sort=notes is also a string, and that column exists, so the query runs and orders the staff screen by the free-text notes column nobody meant to expose. The query builder quotes the identifier, so this is not SQL injection. It is something smaller and still wrong: sorting by notes reveals the relative order of a column the resource does not return. The client picks which of your columns runs the ORDER BY, and the only thing between the client and the column list is a rule that checks for a string.
status is also validated as a string. ?status=checked-in passes. The column holds checked_in, so where('status', 'checked-in') matches nothing and the screen shows an empty list. No error, no log line. The front desk concludes nobody has checked in today.
check_in_from is validated with the date rule. That rule accepts anything PHP can read as a date, which includes 10/01/2026. The controller then hands the string to where() untouched, and the database gets check_in >= '10/01/2026'. The rule and the query disagree about what a date looks like, and the rule is the more generous of the two.
The pattern in all three is the same. Validation proved the value was a string, or a date-like string. The code then used the value as a column name, an exact enum match, and a Y-m-d literal. Passing validation is not the same as being safe to hand to the query builder.
Allowlist the choice, cast the type
Two moves fix the three inputs. Where the risk is which value, the request chooses from a set you wrote down. Where the risk is which type, the controller casts before the value leaves the HTTP layer.
sort becomes an enum. The client picks a name you publish, and the enum maps it to a column. The client never learns the column names, and renaming a column does not change the API:
<?php
declare(strict_types=1);
namespace App\Reservations\ListReservations;
enum ReservationSort: string
{
case ARRIVAL = 'arrival';
case CREATED = 'created';
case TOTAL = 'total';
public function column(): string
{
return match ($this) {
self::ARRIVAL => 'check_in',
self::CREATED => 'created_at',
self::TOTAL => 'total_cents',
};
}
}The request rules use Rule::enum() for both choices and pin the date to one format:
<?php
declare(strict_types=1);
namespace App\Reservations\ListReservations;
use App\Reservations\Reservation\ReservationStatus;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
final class ListReservationsRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
/**
* @return array<string, list<mixed>>
*/
public function rules(): array
{
return [
'sort' => ['sometimes', Rule::enum(ReservationSort::class)],
'status' => ['sometimes', Rule::enum(ReservationStatus::class)],
'check_in_from' => ['sometimes', 'date_format:Y-m-d'],
];
}
}?sort=guest now fails validation with a 422 that names the field. ?status=checked-in fails too, because checked-in is not a backing value of ReservationStatus. 10/01/2026 fails date_format:Y-m-d.
The query itself gets its own object, the read-side counterpart of RequestReservationCommand, so the values that reach the database cannot be raw strings by construction:
<?php
declare(strict_types=1);
namespace App\Reservations\ListReservations;
use App\Reservations\Reservation\ReservationStatus;
use Carbon\CarbonImmutable;
final readonly class ListReservationsQuery
{
public function __construct(
public ReservationSort $sort,
public ?ReservationStatus $status,
public ?CarbonImmutable $checkInFrom,
) {
}
}The controller casts at the boundary. enum() returns the enum case for a valid backing value and the default otherwise. date() with a format returns a Carbon instance parsed with that exact format, or null when the field is absent:
<?php
declare(strict_types=1);
namespace App\Reservations\ListReservations;
use App\Reservations\Reservation\ReservationStatus;
use Illuminate\Contracts\Bus\Dispatcher;
use Illuminate\Http\JsonResponse;
final readonly class ListReservationsController
{
public function __construct(
private Dispatcher $bus,
) {
}
public function __invoke(ListReservationsRequest $request): JsonResponse
{
$reservations = $this->bus->dispatch(new ListReservationsQuery(
sort: $request->enum('sort', ReservationSort::class, ReservationSort::ARRIVAL),
status: $request->enum('status', ReservationStatus::class),
checkInFrom: $request->date('check_in_from', 'Y-m-d')?->toImmutable(),
));
return ListReservationsResource::collection($reservations)->response();
}
}The handler builds the query from typed values. The status binding is an enum case, and the query builder casts a backed enum binding to its value. The date is formatted by us, so the database receives 2026-10-01 no matter what the client typed:
<?php
declare(strict_types=1);
namespace App\Reservations\ListReservations;
use App\Reservations\Reservation\Reservation;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Pagination\LengthAwarePaginator;
final readonly class ListReservationsQueryHandler
{
public function handle(ListReservationsQuery $query): LengthAwarePaginator
{
return Reservation::query()
->with(['guest:id,name', 'room:id,number'])
->when(
$query->status !== null,
fn (Builder $builder) => $builder->where('status', $query->status),
)
->when(
$query->checkInFrom !== null,
fn (Builder $builder) => $builder->where('check_in', '>=', $query->checkInFrom->toDateString()),
)
->orderBy($query->sort->column())
->paginate(25);
}
}Nothing in the handler touches the request. The query goes through the bus the same way RequestReservationCommand does: ReservationsServiceProvider adds ListReservationsQuery::class => ListReservationsQueryHandler::class to its Bus::map, with a use line for each class. Give the handler a ListReservationsQuery from a test or a console command, and it runs the same query. There is no way to hand it guest as a sort column, because ReservationSort has no such case.
Where the line is
The controller is the last place a value is a string from the network. Past that line, every value is the type the code needs: an enum case, a date object, an integer. Validation rules decide what is allowed in. Casting decides what type it is once it is in. A field usually needs both, and the two are not interchangeable. Rule::enum() on status without enum() in the controller would still hand the query a string. enum() in the controller without the rule would turn checked-in into a silent default instead of a 422.
The one thing to remember
A request value is a string or missing until you prove otherwise. Validate and cast at the controller, and let nothing past it that is still a string from the wire.