K
K
KBBS2021-11-05 12:22:18
Laravel
KBBS, 2021-11-05 12:22:18

How to use gte rule in laravel in case of optional fields?

Hello.

I have something like this in my form request

public function rules()
{
    return [
        'min_price' => 'nullable|numeric|min:0',
        'max_price' => 'nullable|numeric|min:0|gte:max_price',
    ];
}

Both fields are optional.
But if I only specify max_price, I get an error that the value must be greater than or equal to min_price.

I don't need to make any of the fields required.
The idea is as follows.
  • The user can only specify min_price and not max_price.
  • The user can only specify max_price and not specify min_price.
  • The user can fill in both fields.
  • The user can leave both fields blank.

And only in the case when both fields are filled, I want to additionally check that the value of max_price is greater than or equal to min_price.
It's just that if min_price is not specified, then this check loses all meaning.

Is there really no way to bypass this and have to write a custom rule?
This is a fairly common case. Doesn't laravel know how to take field optionality into account in such cases?

Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jazzus, 2021-11-05
@KBBS

Remove gte rule from list of rules if $this->filled('min_price')

I
inFureal, 2021-11-05
@inFureal

required_if

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question