Validation rules required_if with other condition (Laravel 5.4)

kesm0 picture kesm0 · Feb 18, 2017 · Viewed 26.4k times · Source

I got a problem with validation rules with nested conditions.

class StoreRequest extends Request
{
        public function authorize(){
        return true;
        }

        public function rules(){
                return [
                    'type_id'     => 'required|integer',
                    'external_id' => 'required_if:type_id,==,3|integer',
                ];
        }
}

Indeed I want to : - check the external_id only if the type_id equal to 3 - and check if it's an integer.

When I post my form, the rules works when I select a type_id equal to 3. But if I select another type_id, like 1 or 2, the validation does not pass :

The external_id must be an integer.

I try to add the nullable condition but required_if does not work anymore

Did you have any idea ?

Answer

Nick A picture Nick A · Jul 16, 2017

Just came across the same problem and found the following answer that seems to work for me:

issue-using-required-if-validation-rule-in-form-builder

     return [
                'type_id'     => 'required|integer',
                'external_id' => 'required_if:type_id,==,3|nullable|integer',
            ];

Result for me:

field not populated, type id not 3 - pass

field not populated, type id 3 - fail - required field

field populated, type id 3, non-integer - fail in integer rule

field populated, type id 3, integer - pass - all good!

note - think nullable rule came in Laravel 5.3