Laravel Complex Conditional Validator

5 months ago

Imagine that, you have two fields to validate.

  • first
  • second

Validation Rules:

  • The first field is required.
  • The second field is required IF the first field has value and that value is equal foo. Then, set the minimum value is 5, maximum value is 50.

So-


    $validator = Validator::make(request()->all(), [
        'first' => 'required',
    ]);

    $validator->sometimes('second', 'required_if:first,true|min:5|max:50', function ($input) {
        return $input->first == 'foo';
    });

Reference: https://laravel.com/docs/master/validation#complex-conditional-validation