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!
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:
// Running validation $this->validate($request, [ 'user_id' => 'bail|required|integer|unique:users,user_id' ]);
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 🙂
nice in laravel 5.1. How about implementing this feature on laravel 5.1 ?
Joel James says
It is even possible in Laravel 5.1 too. But you will have to edit the core file. Tayler merged this to 5.2 only. So this feature will be available from v5.2 by default.
you might need to create custom validation rules, following this bail
Sometimes you may face this same issue and wish to stop running validation rules on an attribute after the first validation failure.