Laravel validation required if field not equal to

Viewed 13556

I have custom validation rule in my controller:

$this->validate($request, [
    'currency' => [
        'required',
        'numeric',
        'min:0',
        'max:7'
    ],
    'price' => [
        'nullable',
        "required_if:currency, !=, 0",
        'numeric',
        'min:1',
        'max:1000000'
    ],
], $messages);

Why work in required_if:currency, ==, 0 and not work in this required_if:currency, !=, 0 case?

In my case price field required only when currency field value not equal to 0

I tired also:

required_unless,currency,0
required_unless:currency,0
3 Answers

required_if:currency, ==, 0 works because the currency value must be equal to any of the values that follow the value name (in this case currency). In other words, price is required in this case if currency is either == or 0.

So the == doesn't mean the usual "equals" in this case. It is just taken as a string value. That is also why required_if:currency, !=, 0 does not work as you expected it to.

To make the price field required only when the currency field value is not equal to 0, you could use required_unless:currency,0.

In other words, price is always required, unless currency is equal to 0.

You can use this:

Rule::requiredIf($request->get('currency') != 0)
Related