Search code examples
phplaravellaravel-5laravel-5.6laravel-validation

Laravel 5.6. Fail, if 2 specific fields are present in the request


I have 2 fields in the request. field1 and field2.

What rules should I define in the FormRequest to fail validation, if both are present?


Solution

  • AFAIK there is no validation rule for this, you could write one, or if it's one-off, you could write a closure:

        'field1' => function ($attribute, $value, $fail) {
            if ($value && $this->input('field2')) {
                return $fail($attribute.' can only be filled when field2 is empty.');
            }
        },
    

    https://laravel.com/docs/5.6/validation#using-closures

    Note: Outside of a FormRequest class, you would need to use something other than $this->input()