'Laravel validation to make sure 2 values are not present at same time

I need to validate a request where if field1 is present, then field2 should be empty and vice versa. How can i achieve this in Laravel?



Solution 1:[1]

You can try this:

$rules = array(
    'field1' => 'required_without:field2',
    'field2' => 'required_without:field1',
);

Solution 2:[2]

From Laravel Docs:

#prohibits:anotherfield,...
If the field under validation is present, no fields in another field can be present, even if empty.

I think this is what you want:

public function rules()
{
  return [
   'field1' => 'prohibits:field2',
   'field2' => 'prohibits:field1',
}

What does this means?

Based on the sample code above we can know once field1 is present, field2 is not allowed to be present. Likewise, once field2 is present, field1 is not allowed to be present.

Hopefully, this can help you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kaleem Shoukat
Solution 2 yungts