Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Validation: bail rule not working

According to Laravel Documentation, bail rule should stop running validation rules after first validation failure.

I have a file outside App\Http\* namespace with the following code in it:

if(Validator::make($params, [
    'email' => 'bail|required|email|max:60|exists:customers,email',
    'password' => 'required|max:60|string',
    'password' => new CustomerCheckPassword($params['email']),
]) -> fails())
    throw new Exception('message here');

Works like a charm, except bail rule from email attribute does not stop the validation when $params['email'] is not contained by customers.email, and goes on to password as well. Do you have any ideas or elegant workarounds for this issue?

like image 369
user8555937 Avatar asked Nov 04 '19 17:11

user8555937


1 Answers

In a different section of the same docs page (it won't link directly to it), it explains that bail only applies to the current attribute. So for instance, if email is missing, it will not check anything after required, but password is a new attribute so it will validate it as normal.

Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute:

One way to accomplish this would be to use the sometimes method

Validator::make($params, [
    'email' => 'bail|required|email|max:60|exists:customers,email',
    'password' => 'required|max:60|string',
])->sometimes('password', new CustomerCheckPassword($params['email']), function ($input) {
    // Check input to decide if rule should execute
});
like image 57
Brian Thompson Avatar answered Nov 08 '22 09:11

Brian Thompson