You need to create your own validation rule.
Modify app/Providers/AppServiceProvider.php
and add this validation rule to the method boot
:
\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;
});
\Validator::replacer(
'empty_if',
function ($message, $attribute, $rule, $parameters) {
return str_replace(
[':other', ':value'],
[$parameters[0], request()->input($parameters[0])],
$message
);
});
(optional) Create an error message in resources/lang/en/validation.php
:
'empty_if' => 'The :attribute field must be empty when :other is :value.',
Then use this rule in the controller (s require_if
, to observe both rules of the original message):
$attributes = request()->validate([
'a' => 'required',
'b' => 'required_if:a,x|empty_if:a,y,z'
]);
It works!
Side note. Perhaps I will create a package for this need with empty_if
and empty_unless
and post a link here
source
share