Home > Mobile >  Laravel - request validation for two nullable fields requiring at least one of them to be not-null
Laravel - request validation for two nullable fields requiring at least one of them to be not-null

Time:08-13

My model has two nullable fields, but at least one of them must be not-null. How do I setup request validation for this ?

$request->validate([        
    'field_1' => ['nullable'],
    'field_2' => ['nullable'],
    ...
]);

thanks

CodePudding user response:

If you have only two filed comparisons then you can use required_without:foo,bar,...

 $request->validate([
        'field_1' => 'required_without:field_2',
        'field_2' => 'required_without:field_1'
    ]);

if it has more than two fields then required_without_all:foo,bar,...

 $request->validate([
        'field_1' => 'required_without_all:field_2,field_3',
        'field_2' => 'required_without_all:field_1,field_3',
        'field_3' => 'required_without_all:field_1,field_2',
    ]);

As per Doc

required_without:foo,bar,...

The field under validation must be present and not empty only when any of the other specified fields are empty or not present.

required_without_all:foo,bar,...

The field under validation must be present and not empty only when all of the other specified fields are empty or not present.

Validation

  • Related