Required field only if another field has a value, must be empty otherwise



PHP Snippet 1:

// Extends the validator
\Validator::extendImplicit(
    'empty_if',
    function ($attribute, $value, $parameters, $validator) {
        $data = request()->input($parameters[0]);
        $parameters_values = array_slice($parameters, 1);
        foreach ($parameters_values as $parameter_value) {
            if ($data == $parameter_value && !empty($value)) {
                return false;
            }
        }
        return true;
    });

// (optional) Display error replacement
\Validator::replacer(
    'empty_if',
    function ($message, $attribute, $rule, $parameters) {
        return str_replace(
            [':other', ':value'], 
            [$parameters[0], request()->input($parameters[0])], 
            $message
        );
    });

PHP Snippet 2:

'empty_if' => 'The :attribute field must be empty when :other is :value.',

PHP Snippet 3:

$attributes = request()->validate([
    'a' => 'required',
    'b' => 'required_if:a,x|empty_if:a,y,z'
]);

PHP Snippet 4:

'b' => 'required_if:a,x'