skip to Main Content

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


  1. Use the withValidator and a sometimes to conditionally add the required rule.

    company_description' => ['string']

    public function withValidator($validator) {
            $validator->sometimes('company_description', 'required', function ($input) {
                return $input->offer_type_id == 1 && $input->use_default_company_description == false;
            });
        }
    
    Login or Signup to reply.
  2. nullable allows the field to be null, which oppose the custom validation rule you are trying to apply when offer_type_id == 1 and use_default_company_description == false. When nullable is present, it takes precedence

    'company_description' => [
            'string',
            'nullable',
            function ($attribute, $value, $fail) {
                $offerType = request()->input('offer_type_id');
                $useDefault = request()->input('use_default_company_description');
        
                // If offer_type_id is 1 and use_default_company_description is false
                if ($offerType == 1 && $useDefault == false) {
                    // Check if the company_description is null or empty
                    if (!request()->filled('company_description')) {
                        $fail('Company description is required.');
                    }
                }
            },
        ],
    

    Kindly note the following

    1. request()->filled(): This helper checks if the input is present and not empty or null
    2. The fail() method will only be triggered if company_description is empty or not provided when offer_type_id == 1 and use_default_company_description == false
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search