laravelvalidationlaravel-formrequest

Both fields can be empty but when filled only one required


I'm making one page in Laravel and validating using Form Request. I have 2 codes on that page.

  1. Coupon Code 2) Promo Code

I want to set conditions in such a way that these codes can be empty but when filled then only one is required.

I've tried this but not getting the proper results.

return [
            'coupon_code' => 'nullable|required_without:promo_code',
            'promo_code' => 'nullable|required_without:coupon_code'
        ];

Solution

  • From your description, it is clear you want to allow these three input pairs:

    1. coupon_code null, promo_code null
    2. coupon_code value, promo_code null
    3. coupon_code null, promo_code value

    Enforcing any of those 3 pairs of values doesn't require any validation rules at all. You can set both rules to nullable, and be fine.

    But reading between the lines, it seems you're asking for this value pair to be rejected:

    1. coupon_code value, promo_code value

    If that's the case, then instead of using required you would use prohibited_unless:

      [
        'promo_code' => [
          'prohibited_unless:coupon_code,null',
        ],
        'coupon_code' => [
          'prohibited_unless:promo_code,null',
        ],
      ]
    

    This assumes you have the default ConvertEmptyStringsToNull middleware in place.