Laravel validator: This field or that field is required, but not both

Recently, I needed to produce a check where one of two fields were required in a form submission, but not both. For example, say we had a house phone number field and a mobile phone number field but we only required one of those upon submission and not both, how can we do that?

I searched the web and found a few interesting articles however I opted to write my own validator, which you can see below.

Validator::extendImplicit('this_or_that', function ($attribute, $value, $parameters, $validator) {
    return (bool) (!empty($value) ^ (array_key_exists($parameters[0], $validator->getData()) && !empty($validator->getData()[$parameters[0]])));

To use this, place the above code in your app/Providers/AppServiceProvider.php file's boot() method. Then see the following code that will go into your controller method:

$this->validate($request, [
    'first_name' => 'required',
    'house_phone_number' => 'this_or_that:mobile_phone_number|number',
    'mobile_phone_number' => 'number',

Hopefully the above code is self explanatory. Just remember not to use the required flag on the two fields that you wish to be "this_or_that" as by using this validator they already have the necessary "required" logic check on them. Also, do not define the "this_or_that" validator more than once. Putting it on one of the two fields (it doesn't matter which) is enough.

Questions? Leave them below.


Comments (0)

Your comment