How to validate that a field must be true if another field is false

Below is a snippet of my validation currently:

'independent_financial_advisor' => 'required|boolean',
'understand_objective' => 'required|boolean',
'confirm_objective' => 'required|boolean',
'understand_term_held' => 'required|boolean',
'tax_relief' => 'required|boolean',

I need to validate that when independent_financial_advisor is false, the remaining 4 fields below must be true. I could not find any Laravel rule which could do this so I thought about using a closure to create a custom rule.

The issue with this is that I don’t know how to reference another field in a closure to check its value.

What is the best way to go about this? Thanks

Answer

I added a custom validation rule called true_if_reference_is_false and passed a parameter to it which is independent_financial_advisor.

So the validation looks like this:

$this->validate($request, [
    'independent_financial_advisor' => 'required|boolean',
    'understand_objective' => 'required|boolean|true_if_reference_is_false:independent_financial_advisor',
    'confirm_objective' => 'required|boolean|true_if_reference_is_false:independent_financial_advisor',
    'understand_term_held' => 'required|boolean|true_if_reference_is_false:independent_financial_advisor',
    'tax_relief' => 'required|boolean|true_if_reference_is_false:independent_financial_advisor'
]);

You need to define this validation rule in AppProvidersAppServiceProvider.php Import Facade Validator.

use IlluminateSupportFacadesValidator;

And define the rule in the boot method:

Validator::extend('true_if_reference_is_false', function ($key, $value, $parameters, $validator) {
    $request = request();
    $keyReference = $parameters[0];
    if ($request->has($parameters[0]) && $request->$keyReference == false)
        return (bool)$request->$key;
    else
        return true;
});

Hope this helps 🙂