Skip to content

Stop Writing Laravel APIs Like This

Insights•
November 30, 2026

Introduction

Your API contract is a promise. Every endpoint tells the client what it accepts, what it does, and what it returns. Every shortcut you take at the edge of the system makes that promise weaker.

The shortcuts feel like features. Mass assignment from $request->validated(), query input passed straight to the builder, one update endpoint that does everything, one Form Request shared by create and update. Each one is convenient on the way in and expensive to undo once a handful of callers depend on it.

These are the four I find in most of the Laravel APIs I review. Each section shows the habit, what it costs, and the explicit version. The Laravel Best Practices: Writing Laravel That Lasts course refactors one reservation API through all four in its Request Handling and API Design chapter; this article is the standalone version.

1. $request->validated() into your models

The classic shortcut:

PHP
<?php declare(strict_types=1); namespace App\Http\Controllers; use App\Http\Requests\StoreUserRequest; use App\Models\User; use Illuminate\Http\JsonResponse; class StoreUserController extends Controller { public function store(StoreUserRequest $request): JsonResponse { $user = User::create($request->validated()); return new JsonResponse(['data' => ['id' => $user->id]], 201); } }

This works until someone adds an admin endpoint that reuses StoreUserRequest. They add is_admin or role_id to the rules because the admin flow needs it. The public signup endpoint now accepts those fields too, even though nobody touched its controller or its tests.

The first sign is a support ticket about a user who has admin access and should not.

validated() returns whatever the request class says passed validation today. Whether a new key reaches the database depends on the model. If the column is in $fillable, or the application calls Model::unguard(), create() writes it. If the column is not fillable, Eloquent drops the key without a word, or throws once Model::shouldBeStrict() is on. In both setups the request class has become the write contract, and the rule that decides what gets written lives in a validation array that someone will edit for an unrelated reason.

$request->all() is the same shortcut with the safety pin pulled: every key the client sent, validated or not, becomes a column write attempt. all() is the obvious version; validated() is the version that passes code review and fails the same way once the rules drift.

Name the fields at the write. Then adding is_admin to a request class does nothing until someone also adds it to the command (a small class that holds one operation's input), the controller line that builds it, and the create() array in the handler (the class that runs the operation).

PHP
<?php declare(strict_types=1); namespace App\Users; use Illuminate\Foundation\Http\FormRequest; final class SignUpRequest extends FormRequest { public function authorize(): bool { return true; } public function rules(): array { return [ 'email' => ['required', 'email', 'unique:users,email'], 'password' => ['required', 'string', 'min:12'], 'name' => ['required', 'string', 'max:255'], ]; } }
PHP
<?php declare(strict_types=1); namespace App\Users; final readonly class SignUpCommand { public function __construct( public string $email, public string $password, public string $name, ) { } }
PHP
<?php declare(strict_types=1); namespace App\Users; use App\Models\User; use Illuminate\Contracts\Hashing\Hasher; final readonly class SignUpCommandHandler { public function __construct(private Hasher $hasher) { } public function handle(SignUpCommand $command): User { return User::query()->create([ 'email' => $command->email, 'name' => $command->name, 'password' => $this->hasher->make($command->password), ]); } }
PHP
<?php declare(strict_types=1); namespace App\Users; use Illuminate\Contracts\Bus\Dispatcher; use Illuminate\Http\JsonResponse; final readonly class SignUpController { public function __construct(private Dispatcher $bus) { } public function __invoke(SignUpRequest $request): JsonResponse { $user = $this->bus->dispatch(new SignUpCommand( email: $request->string('email')->toString(), password: $request->string('password')->toString(), name: $request->string('name')->toString(), )); return new JsonResponse(['data' => ['id' => $user->id]], 201); } }

The controller hands the command to Laravel's command bus, Illuminate\Contracts\Bus\Dispatcher, which runs the handler that the Bus::map() call in section 3 pairs with it. The command holds only the fields it is allowed to hold, and the handler writes only the columns it names. A command and a handler is one shape for this; a single-action class or a named-array create() in the controller name the fields just as well. The discipline is the naming, not the shape.

Telling people to stop piping validated() into models often gets read as "never call validated()". The method is fine for what it is: the validated payload as an array, for logging, an audit trail, or forwarding to a collaborator that already knows its own shape. The specific shortcut is feeding it straight into Model::create() or Model::fill(). validated() does not always return exactly what came in. prepareForValidation() can change the input before the rules run, a dotted rule like address.street produces a nested array, and a sometimes key is present or absent depending on the payload. Look at what comes out before you trust the shape.

The course walks the same fix through a reservation handler in Laravel Mass Assignment Straight From the Request.

2. Trusting the request

This looks harmless:

PHP
<?php declare(strict_types=1); namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; class ListUsersController extends Controller { public function index(Request $request): JsonResponse { $users = User::query() ->where('team_id', $request->input('team_id')) ->orderBy($request->input('sort', 'created_at'), $request->input('direction', 'asc')) ->limit($request->input('limit')) ->select(['id', 'name', 'email']) ->get(); return new JsonResponse(['data' => $users]); } }

Three bugs in this snippet. limit() receives a string or null, and null means no limit at all. orderBy() accepts any column name the client sends, including columns that do not exist or should not be sortable. team_id is whatever the client typed, never cast, never checked against the caller, so any user can list any team; the fix below reads it from the authenticated user instead.

If the column does not exist, the database rejects the query and the client gets a 500. If the column exists but should not be sortable, the response leaks information through the row order itself.

The endpoint is meant for team members. The select keeps salary out of the body, so the developer assumes the column is private. Row order is information:

TEXT
GET /api/users?team_id=42&sort=salary&direction=desc [ { "id": 903, "name": "Carol", "email": "carol@..." }, { "id": 901, "name": "Alice", "email": "alice@..." }, { "id": 902, "name": "Bob", "email": "bob@..." } ]

No salary appears anywhere, and every member of the team now knows Carol earns the most and Bob the least. Repeat with sort=date_of_birth or sort=last_login_ip and each hidden column gives up its ordering the same way.

The fix is an allowlist. If a column is not safe to sort by, it is not a case in the enum, and the request fails with a 422 before the query is built.

PHP
<?php declare(strict_types=1); namespace App\Users; enum UserSort: string { case CREATED_AT = 'created_at'; case NAME = 'name'; case LAST_SEEN_AT = 'last_seen_at'; }
PHP
<?php declare(strict_types=1); namespace App\Users; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; final class ListUsersRequest extends FormRequest { public function authorize(): bool { return $this->user() !== null; } public function rules(): array { return [ 'sort' => ['sometimes', Rule::enum(UserSort::class)], 'direction' => ['sometimes', Rule::in(['asc', 'desc'])], 'limit' => ['sometimes', 'integer', 'min:1', 'max:100'], ]; } }
PHP
<?php declare(strict_types=1); namespace App\Users; use App\Models\User; use Illuminate\Http\JsonResponse; final readonly class ListUsersController { public function __invoke(ListUsersRequest $request): JsonResponse { $sort = $request->enum('sort', UserSort::class) ?? UserSort::CREATED_AT; $users = User::query() ->where('team_id', $request->user()->team_id) ->orderBy($sort->value, $request->string('direction', 'asc')->toString()) ->limit($request->integer('limit', 25)) ->select(['id', 'name', 'email']) ->get(); return new JsonResponse(['data' => $users]); } }

The Form Request allowlists sort and direction, so by the time the controller reads them they are safe to drop into orderBy(). limit goes through integer() with a default of 25, so a request without limit no longer returns every row on the team. enum() returns null, or the default you pass, for any value that is not a backing value of the enum, so it never hands the query a column you did not list; pair it with Rule::enum in the request so a bad value is a 422 instead of a silent fallback. Allowlist where the risk is which value, cast where the risk is which type.

The course does the same for a reservation list in Laravel Validation Is Not Enough.

3. One endpoint, many intents

This is the endpoint that does everything:

PHP
<?php declare(strict_types=1); namespace App\Http\Controllers; use App\Http\Requests\UpdateUserRequest; use App\Models\User; use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Hash; class UpdateUserController extends Controller { public function update(UpdateUserRequest $request, int $userId): JsonResponse { $user = User::findOrFail($userId); if ($request->filled('email')) { $user->email = $request->input('email'); } if ($request->filled('password')) { $user->password = Hash::make($request->input('password')); } if ($request->boolean('cancel_subscription')) { $user->subscription?->cancel(); } if ($request->boolean('archive')) { $user->archived_at = now(); } $user->save(); return new JsonResponse(['data' => ['id' => $user->id]]); } }

One PATCH /users/{id}, four use cases. The validation rules are a union of everything any caller might send. The audit log says "user updated" with no useful detail. The client has to read your source code to know which combinations are legal. And the permission check is either too broad or a chain that mirrors the body:

PHP
<?php declare(strict_types=1); namespace App\Http\Requests; use App\Models\User; use Illuminate\Foundation\Http\FormRequest; class UpdateUserRequest extends FormRequest { public function authorize(): bool { $user = User::findOrFail((int) $this->route('id')); if ($this->filled('email')) { return $this->user()->can('changeEmail', $user); } if ($this->filled('password')) { return $this->user()->can('changePassword', $user); } if ($this->boolean('cancel_subscription')) { return $this->user()->can('cancelSubscription', $user); } if ($this->boolean('archive')) { return $this->user()->can('archive', $user); } return false; } public function rules(): array { return [ 'email' => ['sometimes', 'email'], 'password' => ['sometimes', 'string', 'min:12'], 'cancel_subscription' => ['sometimes', 'boolean'], 'archive' => ['sometimes', 'boolean'], ]; } }

One check per field, and the first match wins. Send email and archive together and only the email policy runs; the archive happens without the archive check.

Split it by intent. Each operation gets its own route, its own request class, and its own command.

TEXT
PATCH /users/{id}/email POST /users/{id}/change-password POST /users/{id}/cancel-subscription POST /users/{id}/archive
PHP
<?php declare(strict_types=1); namespace App\Users; use Illuminate\Foundation\Http\FormRequest; final class ChangeEmailRequest extends FormRequest { public function authorize(): bool { return $this->user()?->can('users.changeEmail') ?? false; } public function rules(): array { return [ 'email' => ['required', 'email', 'unique:users,email'], ]; } }
PHP
<?php declare(strict_types=1); namespace App\Users; final readonly class ChangeEmailCommand { public function __construct( public int $userId, public string $email, ) { } }
PHP
<?php declare(strict_types=1); namespace App\Users; use Illuminate\Contracts\Bus\Dispatcher; use Illuminate\Http\JsonResponse; final readonly class ChangeEmailController { public function __construct(private Dispatcher $bus) { } public function __invoke(ChangeEmailRequest $request, int $userId): JsonResponse { $this->bus->dispatch(new ChangeEmailCommand( userId: $userId, email: $request->string('email')->toString(), )); return new JsonResponse(status: 204); } }

The bus finds ChangeEmailCommandHandler through the Bus::map() call in UsersServiceProvider below, the same wiring lesson Laravel Command Bus for a Use Case Without a Shape sets up. The handlers for these commands are not shown because they have the same shape as SignUpCommandHandler above: load the user, apply the change, save.

authorize() answers a coarse question: may this caller perform this kind of operation at all? The per-target check, whether this caller may change this specific user's email, belongs in the handler, which has already loaded the user for the write. One query instead of two, and a missing user is a 404 from the handler rather than from a Form Request.

Not every endpoint needs a payload. A state change is a URL:

PHP
<?php declare(strict_types=1); namespace App\Users; final readonly class CancelSubscriptionCommand { public function __construct(public int $userId) { } }
PHP
<?php declare(strict_types=1); namespace App\Users; use Illuminate\Foundation\Http\FormRequest; final class CancelSubscriptionRequest extends FormRequest { public function authorize(): bool { return $this->user()?->can('users.cancelSubscription') ?? false; } public function rules(): array { return []; } }
PHP
<?php declare(strict_types=1); namespace App\Users; use Illuminate\Contracts\Bus\Dispatcher; use Illuminate\Http\JsonResponse; final readonly class CancelSubscriptionController { public function __construct(private Dispatcher $bus) { } public function __invoke(CancelSubscriptionRequest $request, int $userId): JsonResponse { $this->bus->dispatch(new CancelSubscriptionCommand(userId: $userId)); return new JsonResponse(status: 204); } }

There is no body because the URL already says what the operation is; the request exists only for authorize(). If you later need a reason code or a cancel-at-period-end flag, you add a rule to the request and a field to the command, and the change stays inside this one endpoint instead of growing a new branch in the shared controller.

This trades some REST orthodoxy for clarity. The parts of REST that matter still hold: resource URLs, GET stays safe and cacheable, DELETE stays idempotent. What you give up is the idea that one PATCH per resource is the only legal way to model a write. A route list that names every operation is a contract a client can read. A single PATCH whose body decides what happens is a contract that lives in your source code.

UsersServiceProvider, registered in bootstrap/providers.php, maps each command to its handler:

PHP
<?php declare(strict_types=1); namespace App\Users; use Illuminate\Support\Facades\Bus; use Illuminate\Support\ServiceProvider; final class UsersServiceProvider extends ServiceProvider { public function boot(): void { Bus::map([ SignUpCommand::class => SignUpCommandHandler::class, ChangeEmailCommand::class => ChangeEmailCommandHandler::class, CancelSubscriptionCommand::class => CancelSubscriptionCommandHandler::class, ]); } }

The course splits a reservation PATCH the same way in Laravel API Design: One Endpoint Doing Four Things.

4. One Form Request for create and update

Here is the Form Request you have written:

PHP
<?php declare(strict_types=1); namespace App\Users; use Illuminate\Foundation\Http\FormRequest; final class UserRequest extends FormRequest { public function authorize(): bool { return $this->user() !== null; } public function rules(): array { return [ 'email' => ['required', 'email', 'unique:users,email'], 'password' => ['required', 'string', 'min:12'], 'name' => ['required', 'string', 'max:255'], ]; } }

Reused for PATCH /users/{id}, unique:users,email fails on the user's own email and required on password forces callers to send one on every update. You patch it with sometimes everywhere, and now create accepts partial payloads too.

Create and update are different operations, so they get different classes:

PHP
<?php declare(strict_types=1); namespace App\Users; use Illuminate\Foundation\Http\FormRequest; final class CreateUserRequest extends FormRequest { public function authorize(): bool { return $this->user()?->can('users.create') ?? false; } public function rules(): array { return [ 'email' => ['required', 'email', 'unique:users,email'], 'password' => ['required', 'string', 'min:12'], 'name' => ['required', 'string', 'max:255'], ]; } }
PHP
<?php declare(strict_types=1); namespace App\Users; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Validation\Rule; final class UpdateUserRequest extends FormRequest { public function authorize(): bool { return $this->user()?->can('users.update') ?? false; } public function rules(): array { $userId = (int) $this->route('id'); return [ 'email' => ['sometimes', 'email', Rule::unique('users', 'email')->ignore($userId)], 'name' => ['sometimes', 'string', 'max:255'], ]; } }

Password is not here, because changing a password is its own endpoint (see section 3); email stays only for teams that keep a general PATCH /users/{id}. Email uniqueness ignores the current user. Create and update no longer fight each other over required versus sometimes.

The course shows the same split for requesting and re-dating a reservation in Laravel Form Request Shared by Create and Update.

Where to start on an API that already ships

Do not rewrite it. The next time a ticket lands on an endpoint, split that endpoint: give it its own request class, name the fields its handler writes, and allowlist whatever it sorts or filters by. The old shared classes keep serving the routes nobody has touched, and each one disappears the day its last route is migrated. An API fixed this way never has a big-bang release, and every improvement ships attached to work someone already asked for.