Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Conditional validation rules in Laravel 8.x

Sometimes, you might end up in a situation where you would want to add certain validation rules for fields.

Now, Laravel already has a somtimes method in the Illuminate\Support\Facades\Validator facade that can be used to only add certain validation rules if the Closure passed to it returns true. But that’s quite verbose if you ask me.

There was a need for something simple and that’s where a when method is added to the Illuminate\Validation\Rule class.

The Rule::when() method

As I said, Laravel 8.x now comes with a handy Rule::when() method that can be used to conditionally add certain validation rules on the specified fields.

Here’s how it works.

use Illuminate\Validation\Rule;

    'name' => 'required|string|min:6',
    'password' => ['required', 'string', Rule::when(true, ['min:5', 'confirmed'])],

As you can tell, the Rule::when() method accepts two parameters. The parameter is where pass in the conditional based on which you want to include the validation rules if it’s truthy.

The second parameter is an array of all the validation rules that need to be added based on the conditional.

In my opinion, this is quite concise and elegant than using the sometimes() method I mentioned previously.

Passing in the default rules

Now, when you want to specify the alternative/default set of validation rules when the condition becomes false, you can pass in a third parameter to the Rule::when() method as an array like so.

    ['min:5', 'confirmed'], 

So, in this case, the required validation rule will kick in if the $truthyCondition becomes false. This behaviour is available from the version 8.56.0.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a


👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.