How to stop validating a field if the dependant field is invalid? – Laravel

  laravel, laravel-validation

I am trying to validate a field based on the validity of another field and cant seem to find the answer. Either I am so dumb at searching or its painfully obvious, but I am not able to find a satisfying answer so asking here.

I have a form where I create a unit. The unit belongs to a block and the block belongs to a class. In my form, I have fields to select a class then the block of that class. What I am tring to achive is validate the block and my rule looks like this.

"block_id" => 'required|integer|min:1|exists:blocks,id,class_id,'.$request->input('class_id'),

the class_id is being validated prior to this rule like so

"class_id" => 'required|integer|min:1|exists:classes,id',

what I am trying to achive is to stop validating the block_id if the class_id is not valid.

I am also fine with stoping the validation altogether if the class_id is not valid because I am already validating the fields from fron-end. and this is an extra layer of security. so I am not conserned about user experience (because a normal user will not post invalid data).

How can I achive this?

My first guess is to validate the class_id first like

$request->validate([
    "class_id" => 'required|integer|min:1|exists:classes,id'
]);

then carry out the remaining validation rules. But then I will have to validate request twise(don’t know if it matters any way).

Is there a simple solution to this like $request->validate($rules, halt on first failure = true) kind of option?. My instincts says there should be one but I am unable to find it.

Thanks in advance 🙂

PS: I did ask this question a few weeks back but got no response so reposting to see if there really is an answer here

Source: Laravel

Leave a Reply