Tinkerwell - The PHP Scratchpad

Let's talk about Form Requests

Published on by

Let's talk about Form Requests image

Form Requests are best known for moving your validation logic from your web controllers into a class that will pre-validate for you. They are fantastic, and I lean on them heavily all the time. What else can we do with Form Requests, though?

Beyond adding your methods and calling them inside your controllers, there are a few methods often not used on your form requests that you can lean on to add extra superpowers to your application.

Preparing your input for validation

This method is fantastic when you must transform or add more to the request before the validator starts. The docs show an example of merging in a slug to something, which is helpful, but how about another example?

protected function prepareForValidation(): void
{
$this->merge([
'locale' => $this->user()->locale,
]);
}

We are merging the authenticated users' locale into the request - so we may perform dynamic validation based on the users' locale. Let's say we have limits in place in our application right now, which means that users from Wales (where I live) must add things in a specific format. Random, but I have seen a few use cases as a developer where this might have been useful.

We could even replace content dynamically in this method.

protected function prepareInputForValidation(): void
{
$replace = match ($this->user()->locale) {
'en_GB' => 17.5,
'en_US' => 10.0,
'de_DE' => 12.5,
};
 
$this->replace([
'tax_percentage' => $replace,
]);
}

Here, we dynamically change the tax percentage based on the users' locale. This is useful if you have specific tax rates as part of your import tax as a distributor.

Passed Validation

Much like preparing for validation, we can tap into the after-validation passed, standardize, or format request data into a specific format. As someone who works with data daily, this is very useful.

protected function passedValidation(): void
{
$this->replace([
'name' => Str::uppercase($this->name),
]);
}

Again, these are not the most useful examples - but there is a lot you could do if you wanted, from turning properties into Value Objects for working with money to checking the content for spam.

Failed Authorization

Typically when your form request fails authorization, the framework will throw an AuthorizationException. For 99% of use cases, this is all you need. However, there are a few more obscure times when you want to avoid throwing an exception like this. Let's say you are capturing webhooks from a third-party API, and throwing an Authorization Exception will create weird, uncontrollable behavior in this third party. Instead, you could fail quietly by overriding this method in your form request.

protected function failedAuthorization(): void
{
Log::info('Failed authorization for webhook capture ....');
}

These are just a handful of the methods available on a Form Request, not to mention all those available using Laravel Precognition. But as I mentioned earlier, we can add our methods - allowing us to extend the functionality of our Form Requests a little more. A perfect example is the Laravel Breeze source code, where an authenticate method is added to the LoginRequest so the controller code can be simplified further.

Let's look at an example of a controller that I may typically write:

final class StoreController
{
public function __construct(
private readonly StoreCommand $command,
) {}
 
public function __invoke(StoreRequest $request): Responsable
{
try {
$this->command->handle(
instance: new Instance(
name: $request->string('name')->toString(),
),
);
} catch (Throwable $exception) {
throw new FailedToCreateInstance(
message: 'Failed to create a new instance.',
previous: $exception,
);
}
 
return new CreatedResponse();
}
}

This is a simplified controller where I use a creative class to send through a Data Object to keep my code consistent and clean how I like it. We can simplify our code more by leaning on our form request.

final class StoreController
{
public function __construct(
private readonly StoreCommand $command,
) {}
 
public function __invoke(StoreRequest $request): Responsable
{
try {
$this->command->handle(
instance: $request->dto(),
);
} catch (Throwable $exception) {
throw new FailedToCreateInstance(
message: 'Failed to create a new instance.',
previous: $exception,
);
}
 
return new CreatedResponse();
}
}

This looks similar, but imagine we are building something ten times more complex with many more request fields that we need to map to our data object - our controller will get big and messy in no time. All we have done here is move the creation of our Data Object to a method on the form request - nothing technical at all.

The limits of what you can do on your form requests are only limited by your imagination, but make sure you use them wisely. They aren't there to replace your application logic, remember! It is essential to ensure your application logic is always accessible and readable and not lost in the sea of framework logic or request validation.

Steve McDougall photo

Educator and Content creator, freelance consultant, API evangelist

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Cut PHP Code Review Time & Bugs into Half with CodeRabbit logo

Cut PHP Code Review Time & Bugs into Half with CodeRabbit

CodeRabbit is an AI-powered code review tool that specializes in PHP and Laravel, running PHPStan and offering automated PR analysis, security checks, and custom review features while remaining free for open-source projects.

Cut PHP Code Review Time & Bugs into Half with CodeRabbit
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
A new beta of Laravel Wayfinder just dropped image

A new beta of Laravel Wayfinder just dropped

Read article
Ben Bjurstrom: Laravel is the best Vibecoding stack for 2026 image

Ben Bjurstrom: Laravel is the best Vibecoding stack for 2026

Read article
Laravel Altitude - Opinionated Claude Code agents and commands for TALL stack development image

Laravel Altitude - Opinionated Claude Code agents and commands for TALL stack development

Read article
JSON:API Resource in Laravel 12.45 image

JSON:API Resource in Laravel 12.45

Read article
Caching With MongoDB for Faster Laravel Apps image

Caching With MongoDB for Faster Laravel Apps

Read article
Laravel 12.44 Adds HTTP Client afterResponse() Callbacks image

Laravel 12.44 Adds HTTP Client afterResponse() Callbacks

Read article