Laravel Bail – Stopping On First Validation Failure

Today let’s see what Laravel Bail rule does for you ūüôā

Out of the box, Laravel provides many useful and generic validation rules. But in my opinion the Laravel documentation is not that good. Sometimes we may not find the required thing in documentation but still it is available through code!

Here comes your responsibility. Why don’t you contribute the missing documentation to Laravel instead of complaining about it? Ha,¬†I was trolling myself. We all can contribute to Laravel in GitHub.

Last week I went through a scenario where I wanted to validate a user_id field. The requirement was, user_id should be required, unique and integer . So I have added validation using Laravel Validator class.

My validation was working. But when my QA team started testing, they found that it throws a database error when they enter alphabet characters in user_id field. Yes, they were right. Laravel was validating all the rules. So when I enter an alpha value in user_id field, required rule passed, integer rule failed and unique rule thrown a db error. This was because it was given only to accept integer value in db schema. The only available solution was writing a custom validation.

Sometimes you may face this same issue and wish to stop running validation rules on an attribute after the first validation failure. For my project, I have developed a solution for this. Since Laravel is an opensource project and everybody can contribute to it, I sent a pull request to Laravel through GitHub with the solution. Good news is that they have merged it with the Validator class and now everyone can use it in Laravel 5.2.

To do so, assign the bail rule to the attribute:

In this example, if the required rule on the user_id¬†attribute fails, the unique rule will not be checked. Rules will be validated in the order they are assigned. That means, rules will be checked one by one. So it will not go to next rule if previous rule was a failure. All you have to do is, use the bail rule and assign the other rules in the order so that they won’t break.

Love Laravel, keep coding ūüôā

There are 2 comments

Your email address will not be published. Required fields are marked *