Allowlist Sort Columns With an Enum
A sort parameter validated as string lets the client pick the column in ORDER BY. ?sort=notes runs and orders the staff screen by a free-text column the API never returns, which leaks its relative order. ?sort=guest passes the rule and then fails with a 500, because reservations has no guest column. The query builder wraps column names in backticks and doubles any backtick inside them (MySqlGrammar::wrapValue), so this is not SQL injection. The remaining problem is that the client chooses from your whole column list, including columns that were never meant to be public.
Don't do this
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Reservation;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
final readonly class ListReservationsController
{
public function __invoke(Request $request): JsonResponse
{
$request->validate([
'sort' => ['sometimes', 'string'],
]);
$reservations = Reservation::query()
->orderBy($request->input('sort', 'check_in'))
->paginate(25);
return new JsonResponse($reservations);
}
}Do this instead
<?php
declare(strict_types=1);
namespace App\Reservations;
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',
};
}
}<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Models\Reservation;
use App\Reservations\ReservationSort;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
final readonly class ListReservationsController
{
public function __invoke(Request $request): JsonResponse
{
$request->validate([
'sort' => ['sometimes', Rule::enum(ReservationSort::class)],
]);
$sort = $request->enum('sort', ReservationSort::class, ReservationSort::ARRIVAL);
$reservations = Reservation::query()
->orderBy($sort->column())
->paginate(25);
return new JsonResponse($reservations);
}
}The client now picks a name you published, and the enum maps it to a column. Renaming total_cents changes one line in the enum and nothing in the API. You need both halves: Rule::enum() turns ?sort=guest into a 422, and $request->enum() turns the validated string into a ReservationSort. The third argument is the default for an absent or unknown value.