I have validation in Laravel 10 that contains validation for company_description. I want it to be required when two other fields have specified values. I got this code:
'company_description' => [
'string',
'nullable',
function ($attribute, $value, $fail) {
if (request()->input('offer_type_id') == 1 && request()->input('use_default_company_description') == false) {
if (empty($value) || $value == '') {
$fail('Company description is required.');
}
}
},
],
but its not working. If nullable is removed its working, but I need this field to be nullable. What am I doing wrong?
2
Answers
Use the
withValidator
and asometimes
to conditionally add therequired
rule.company_description' => ['string']
nullable allows the field to be null, which oppose the custom validation rule you are trying to apply when
offer_type_id == 1
anduse_default_company_description == false
. When nullable is present, it takes precedenceKindly note the following
fail()
method will only be triggered ifcompany_description
is empty or not provided whenoffer_type_id == 1
anduse_default_company_description == false