Valid validators validating data

Published on:

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!

What people say about me

Aaron Francis

Aaron Francis

Founder @ Try Hard Studies

Steve is one of the most thorough and thoughtful educators I've seen. He puts in a ton of effort and it clearly shows.
Alex Six

Alex Six

Head of Developer Relations @ Filament PHP

Steve is the teacher you wish you had in school. He’s informative, entertaining, and passionate about what he does. I’m always excited to see more of Steve’s content!
Brent Roose

Brent Roose

Developer Advocate @ jetBrains

To me, there's one word that comes to mind: 'passion'. There are only a handful of people with the same passion for programming as Steve.
Chris Miller

Chris Miller

Lead Developer @ MMS Marketing

Steve is a great developer with a wealth of knowledge that has contributed to many projects we have. His passion for API means we benefit from his aim for the best
Davor Minchorov

Davor Minchorov

Senior PHP Engineer @ Adeva

Steve is an awesome guy who knows a thing or two about APIs. I’ve learned so much from his content on his YouTube channel as well as his API video course.
Eric Barnes

Eric Barnes

Founder @ Laravel News

Steve is an awesome writer and communicator, he can take complex problems and communicate them in a way that anyone can understand.
Gary Clarke

Gary Clarke

YouTuber @ Gary Clarke Tech

Steve is highly engaging and an expert in what he does. I bookmark everything he publishes and refer back to it on a regular basis. The API king!
Aaron Francis

Aaron Francis

Founder @ Try Hard Studies

Steve is one of the most thorough and thoughtful educators I've seen. He puts in a ton of effort and it clearly shows.
Alex Six

Alex Six

Head of Developer Relations @ Filament PHP

Steve is the teacher you wish you had in school. He’s informative, entertaining, and passionate about what he does. I’m always excited to see more of Steve’s content!
Brent Roose

Brent Roose

Developer Advocate @ jetBrains

To me, there's one word that comes to mind: 'passion'. There are only a handful of people with the same passion for programming as Steve.
Chris Miller

Chris Miller

Lead Developer @ MMS Marketing

Steve is a great developer with a wealth of knowledge that has contributed to many projects we have. His passion for API means we benefit from his aim for the best
Davor Minchorov

Davor Minchorov

Senior PHP Engineer @ Adeva

Steve is an awesome guy who knows a thing or two about APIs. I’ve learned so much from his content on his YouTube channel as well as his API video course.
Eric Barnes

Eric Barnes

Founder @ Laravel News

Steve is an awesome writer and communicator, he can take complex problems and communicate them in a way that anyone can understand.
Gary Clarke

Gary Clarke

YouTuber @ Gary Clarke Tech

Steve is highly engaging and an expert in what he does. I bookmark everything he publishes and refer back to it on a regular basis. The API king!
Aaron Francis

Aaron Francis

Founder @ Try Hard Studies

Steve is one of the most thorough and thoughtful educators I've seen. He puts in a ton of effort and it clearly shows.
Alex Six

Alex Six

Head of Developer Relations @ Filament PHP

Steve is the teacher you wish you had in school. He’s informative, entertaining, and passionate about what he does. I’m always excited to see more of Steve’s content!
Brent Roose

Brent Roose

Developer Advocate @ jetBrains

To me, there's one word that comes to mind: 'passion'. There are only a handful of people with the same passion for programming as Steve.
Chris Miller

Chris Miller

Lead Developer @ MMS Marketing

Steve is a great developer with a wealth of knowledge that has contributed to many projects we have. His passion for API means we benefit from his aim for the best
Davor Minchorov

Davor Minchorov

Senior PHP Engineer @ Adeva

Steve is an awesome guy who knows a thing or two about APIs. I’ve learned so much from his content on his YouTube channel as well as his API video course.
Eric Barnes

Eric Barnes

Founder @ Laravel News

Steve is an awesome writer and communicator, he can take complex problems and communicate them in a way that anyone can understand.
Gary Clarke

Gary Clarke

YouTuber @ Gary Clarke Tech

Steve is highly engaging and an expert in what he does. I bookmark everything he publishes and refer back to it on a regular basis. The API king!
Aaron Francis

Aaron Francis

Founder @ Try Hard Studies

Steve is one of the most thorough and thoughtful educators I've seen. He puts in a ton of effort and it clearly shows.
Alex Six

Alex Six

Head of Developer Relations @ Filament PHP

Steve is the teacher you wish you had in school. He’s informative, entertaining, and passionate about what he does. I’m always excited to see more of Steve’s content!
Brent Roose

Brent Roose

Developer Advocate @ jetBrains

To me, there's one word that comes to mind: 'passion'. There are only a handful of people with the same passion for programming as Steve.
Chris Miller

Chris Miller

Lead Developer @ MMS Marketing

Steve is a great developer with a wealth of knowledge that has contributed to many projects we have. His passion for API means we benefit from his aim for the best
Davor Minchorov

Davor Minchorov

Senior PHP Engineer @ Adeva

Steve is an awesome guy who knows a thing or two about APIs. I’ve learned so much from his content on his YouTube channel as well as his API video course.
Eric Barnes

Eric Barnes

Founder @ Laravel News

Steve is an awesome writer and communicator, he can take complex problems and communicate them in a way that anyone can understand.
Gary Clarke

Gary Clarke

YouTuber @ Gary Clarke Tech

Steve is highly engaging and an expert in what he does. I bookmark everything he publishes and refer back to it on a regular basis. The API king!
Jack Ellis

Jack Ellis

Co-Founder @ Fathom Analytics

Steve is one of the top API experts in the world and has been teaching our community for years.
Laravel Jutsu

Laravel Jutsu

YouTuber @ Laravel Jutsu

Steve has a profound mastery of APIs and a public-serving teaching approach.
Luke Downing

Luke Downing

Educator @ Laracasts

Steve is a stream of knowledge. If you like clean, strict code and silky APIs, there’s nobody I’d sooner turn to for advice!
Sam Carré

Sam Carré

Head of Engineering @ Plannr CRM

Steve’s enthusiasm and positive attitude makes his educational content super easy to digest and makes learning new tools and languages really fun.
Peter Thomson

Peter Thomson

Chief Technology Officer @ Ice House Ventures

Steve is an absolute weapon. We came for the APIs but we stayed for the clean code, robust systems architecture and deep knowledge of Laravel conventions. Steve made our code faster, more stable and easier to maintain ourselves in the future.
Stephen Rees-Carter

Stephen Rees-Carter

Friendly Hacker @ Valorin Security

Steve is one of my favourite people. He has a huge passion for teaching developers about APIs and good coding practices.
Steven Tey

Steven Tey

Founder @ Dub.co

Steve brings knowledge and passion to the community, with easy to follow content that adds real value to any company that uses him.
Jack Ellis

Jack Ellis

Co-Founder @ Fathom Analytics

Steve is one of the top API experts in the world and has been teaching our community for years.
Laravel Jutsu

Laravel Jutsu

YouTuber @ Laravel Jutsu

Steve has a profound mastery of APIs and a public-serving teaching approach.
Luke Downing

Luke Downing

Educator @ Laracasts

Steve is a stream of knowledge. If you like clean, strict code and silky APIs, there’s nobody I’d sooner turn to for advice!
Sam Carré

Sam Carré

Head of Engineering @ Plannr CRM

Steve’s enthusiasm and positive attitude makes his educational content super easy to digest and makes learning new tools and languages really fun.
Peter Thomson

Peter Thomson

Chief Technology Officer @ Ice House Ventures

Steve is an absolute weapon. We came for the APIs but we stayed for the clean code, robust systems architecture and deep knowledge of Laravel conventions. Steve made our code faster, more stable and easier to maintain ourselves in the future.
Stephen Rees-Carter

Stephen Rees-Carter

Friendly Hacker @ Valorin Security

Steve is one of my favourite people. He has a huge passion for teaching developers about APIs and good coding practices.
Steven Tey

Steven Tey

Founder @ Dub.co

Steve brings knowledge and passion to the community, with easy to follow content that adds real value to any company that uses him.
Jack Ellis

Jack Ellis

Co-Founder @ Fathom Analytics

Steve is one of the top API experts in the world and has been teaching our community for years.
Laravel Jutsu

Laravel Jutsu

YouTuber @ Laravel Jutsu

Steve has a profound mastery of APIs and a public-serving teaching approach.
Luke Downing

Luke Downing

Educator @ Laracasts

Steve is a stream of knowledge. If you like clean, strict code and silky APIs, there’s nobody I’d sooner turn to for advice!
Sam Carré

Sam Carré

Head of Engineering @ Plannr CRM

Steve’s enthusiasm and positive attitude makes his educational content super easy to digest and makes learning new tools and languages really fun.
Peter Thomson

Peter Thomson

Chief Technology Officer @ Ice House Ventures

Steve is an absolute weapon. We came for the APIs but we stayed for the clean code, robust systems architecture and deep knowledge of Laravel conventions. Steve made our code faster, more stable and easier to maintain ourselves in the future.
Stephen Rees-Carter

Stephen Rees-Carter

Friendly Hacker @ Valorin Security

Steve is one of my favourite people. He has a huge passion for teaching developers about APIs and good coding practices.
Steven Tey

Steven Tey

Founder @ Dub.co

Steve brings knowledge and passion to the community, with easy to follow content that adds real value to any company that uses him.
Jack Ellis

Jack Ellis

Co-Founder @ Fathom Analytics

Steve is one of the top API experts in the world and has been teaching our community for years.
Laravel Jutsu

Laravel Jutsu

YouTuber @ Laravel Jutsu

Steve has a profound mastery of APIs and a public-serving teaching approach.
Luke Downing

Luke Downing

Educator @ Laracasts

Steve is a stream of knowledge. If you like clean, strict code and silky APIs, there’s nobody I’d sooner turn to for advice!
Sam Carré

Sam Carré

Head of Engineering @ Plannr CRM

Steve’s enthusiasm and positive attitude makes his educational content super easy to digest and makes learning new tools and languages really fun.
Peter Thomson

Peter Thomson

Chief Technology Officer @ Ice House Ventures

Steve is an absolute weapon. We came for the APIs but we stayed for the clean code, robust systems architecture and deep knowledge of Laravel conventions. Steve made our code faster, more stable and easier to maintain ourselves in the future.
Stephen Rees-Carter

Stephen Rees-Carter

Friendly Hacker @ Valorin Security

Steve is one of my favourite people. He has a huge passion for teaching developers about APIs and good coding practices.
Steven Tey

Steven Tey

Founder @ Dub.co

Steve brings knowledge and passion to the community, with easy to follow content that adds real value to any company that uses him.

© 2025 JustSteveKing. All rights reserved.