Laravel Validation

Published on by

Laravel Validation image

Validation is a must-have for any modern project, and in Laravel, it is super simple to get started. Within your controller methods, you can call a method, pass in the request, and an array of the rules you wish to validate with.

Is this approach the right way? Is it wrong to do it this way? Of course not, and anyone who tells you otherwise needs a slap with a wet fish. There is nothing wrong with this approach; it works and is testable. The important thing to remember is that while it can be improved, it might not need improving.

In this tutorial, I will walk you through my journey of validation within Laravel, what changes I made and why. Let's start at the beginning.

When I started with Laravel, I did what the documentation told me, plain and simple. I would extend app/Http/Controller and call $this->validate at this point. My controllers were resourceful. My typical store method would look a little like the following, modernized to today's syntax:

namespace App\Http\Controllers\Api;
 
class PostController extends Controller
{
public function store(Request $request): JsonResponse
{
$this->validate($request, [
'title' => 'required|string|min:2|max:255',
'content' => 'required|string',
'category_id' => 'required|exists:categories,id',
]);
 
$post = Post::query()->create(
attributes: [
...$request->validated(),
'user_id' => auth()->id(),
],
);
 
return new JsonResponse(
data: new PostResource(
resource: $post,
),
status: Http::CREATED->value,
);
}
}

Aside from the creation logic, there is nothing wrong with how this validation works. I can test it and manage it, and I know it will validate how I need it to. So if your validation looks like this, good job!

I then moved to invokable controllers, as I preferred to keep things simpler - it looked the same at this point, just with an invoke method instead of a store method.

namespace App\Http\Controllers\Api\Posts;
 
class StoreController extends Controller
{
public function __invoke(Request $request): JsonResponse
{
$this->validate($request, [
'title' => 'required|string|min:2|max:255',
'content' => 'required|string',
'category_id' => 'required|exists:categories,id',
]);
 
$post = Post::query()->create(
attributes: [
...$request->validated(),
'user_id' => auth()->id(),
],
);
 
return new JsonResponse(
data: new PostResource(
resource: $post,
),
status: Http::CREATED->value,
);
}
}

After this, I discovered how helpful Form Requests were - and how encapsulating my validation within these classes helped me. From there, my controller changed again. This time it looked like the following:

namespace App\Http\Controllers\Api\Posts;
 
class StoreController
{
public function __invoke(StoreRequest $request): JsonResponse
{
$post = Post::query()->create(
attributes: [
...$request->validated(),
'user_id' => auth()->id(),
],
);
 
return new JsonResponse(
data: new PostResource(
resource: $post,
),
status: Http::CREATED->value,
);
}
}

I no longer needed to extend the base controller as I didn't need the validate method. I could easily inject the form request into my controllers invoke method, and all data would be pre-validated. This made my controllers super small and lightweight, as I had pushed validation to a dedicated class. My form request would look something like this:

namespace App\Http\Requests\Api\Posts;
 
class StoreRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
 
public function rules(): array
{
return [
'title' => ['required', 'string', 'min:2', 'max:255',]
'content' => ['required', 'string'],
'category_id' => ['required', 'exists:categories,id'],
];
}
}

For a while, I stuck with this style validation, as again, there is nothing wrong with it. If your validation looks like this, good job! Again this is scalable, testable, and repeatable. You can inject this anywhere you are using HTTP requests and need validation.

Where do we go from here, though? How could we improve this? This is a question I asked myself and was stuck for quite some time. Let me explain a scenario that made me question how this could be approached.

Imagine you have a project that allows the creation of posts through an API, a web interface, and perhaps the command line. The API and web interface can share the form request, as both can be injected into the controller. How about the command line? Do we need to repeat the validation for this? Some might argue that you don't need to validate the command line to the same extent, but you will want to add some validation.

I have been playing around with the idea of validators for a while. It is nothing new, so I have no idea why it took so long to figure it out! Validators, at least for me, were classes containing the rules and information essential to validate any request - HTTP or otherwise. Let me show you how one might look:

namespace App\Validators\Posts;
 
class StoreValidator implements ValidatorContract
{
public function rules(): array
{
return [
'title' => ['required', 'string', 'min:2', 'max:255',]
'content' => ['required', 'string'],
'category_id' => ['required', 'exists:categories,id'],
];
}
}

It starts simple, just a place I wanted to centralize the storage of these validation rules. From there, I could extend it as I needed to.

namespace App\Validators\Posts;
 
class StoreValidator implements ValidatorContract
{
public function rules(): array
{
return [
'title' => ['required', 'string', 'min:2', 'max:255',]
'content' => ['required', 'string'],
'category_id' => ['required', 'exists:categories,id'],
];
}
 
public function messages(): array
{
return [
'category_id.exists' => 'This category does not exist, you Doughnut',
];
}
}

I could add things like messages for when I wanted to customize the validation messages. I could add more methods to encapsulate more validation logic. But how does this look in practice? Let's revisit the Store Controller example. Our controller will look the same as we have already moved validation out, so let's instead look at the form request:

namespace App\Http\Requests\Api\Posts;
 
class StoreRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
 
public function rules(): array
{
return (new StoreValidator())->rules();
}
}

As simple as that, I can switch an array stuck in a class and replace it with a class specific to how we want to store and validate this information.

I have seen another approach that I feel is good and bad. Let me talk you through it. I have seen some people keep their validation rules within their Eloquent Models. Now I am not 100% sure on this one, as it feels like we would be mixing purposes a little - however, it is also ingenious. As what you want to do is keep the rules around how this Model is created within the model itself. It knows its own rules. This would look a little like the following:

namespace App\Models;
 
class Post extends Model
{
public static array $rules = [
'title' => ['required', 'string', 'min:2', 'max:255',]
'content' => ['required', 'string'],
'category_id' => ['required', 'exists:categories,id'],
];
 
// The rest of your model here.
}

This could be used in a form request easily and stays with your model, so you can control it from one central point in a class that cares about this.

namespace App\Http\Requests\Api\Posts;
 
class StoreRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
 
public function rules(): array
{
return Post::$rules;
}
}

These are a few ways in which you can validate the data. All are correct, and all can be tested. Which way do you prefer to handle your validation? Do you have a way not mentioned here or in the docs? Let us know on Twitter!

Steve McDougall photo

Technical writer at Laravel News, Developer Advocate at Treblle. API specialist, veteran PHP/Laravel engineer. YouTube livestreamer.

Cube

Laravel Newsletter

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

image
Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Forge
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

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

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
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
Bacancy logo

Bacancy

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

Bacancy
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

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
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
All Green logo

All Green

All Green is a SaaS test runner that can execute your whole Laravel test suite in mere seconds so that you don't get blocked – you get feedback almost instantly and you can deploy to production very quickly.

All Green
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with VILT and TALL stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a 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
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Property Hooks Get Closer to Becoming a Reality in PHP 8.4 image

Property Hooks Get Closer to Becoming a Reality in PHP 8.4

Read article
Asserting Exceptions in Laravel Tests image

Asserting Exceptions in Laravel Tests

Read article
Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4 image

Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4

Read article
Basset is an alternative way to load CSS & JS assets image

Basset is an alternative way to load CSS & JS assets

Read article
Integrate Laravel with Stripe Connect Using This Package image

Integrate Laravel with Stripe Connect Using This Package

Read article
The Random package generates cryptographically secure random values image

The Random package generates cryptographically secure random values

Read article