Using a trait to communicate intent

Don't make future devs guess

Joel Clermont
Joel Clermont
2024-06-07

The vast majority of our form requests define validation rules. In fact, that's the first thing I think of with form requests: that they're for validation.

But every once in a while, we'll create a form request that isn't applying any validation rules. Maybe it's used for some special authorization logic instead.

Laravel is fine with that. You can define an empty rules array, or you can even omit the rules method altogether, and everything will work fine.

However, some future developer looking at this code may be confused. Did you forget to include rules, or was this intentional?

To solve that problem, we define a HasNoRules trait, and use it in the form request to clearly document our intention.

trait HasNoRules
{
    public function rules(): array
    {
        return [];
    }
}

Now the next developer, which could also be you in the future, doesn't have to guess at the intent.

Here to help,

Joel

P.S. Validation is one of my favorite Laravel topics. Check out Mastering Laravel Validation Rules to find out more.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.