Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

SGUserFace's avatar

rules

Why these rules

'more_than' => 'required|integer|gt:less_than',

'less_than' => 'required|integer|lt:more_than',

Returns me an error only when one of the fields is empty

"The values under comparison must be of the same type"

0 likes
8 replies
Borisu's avatar

The lt rule checks if the value is numeric first. If one field is empty it's value will be null and thus it won't pass the initial check.

Borisu's avatar

Sorry I was wrong. The actual code is this:

// ValidatesAttributes.php
protected function requireSameType($first, $second)
    {
        if (gettype($first) != gettype($second)) {
            throw new InvalidArgumentException('The values under comparison must be of the same type');
        }
    }

So just do a dd() there to see what exactly the function is getting.

Borisu's avatar

Well that would be really difficult to say without seeing the form and the rest of the setup you have. I'll try it locally and come back to you.

Borisu's avatar

So I've got it. If the less_than value is missing, then the required rule for the more_than is valid. Then the more_than will get to the greater than rule and try to access the less_than value, which is null and thus the types don't match. To make it work you have to make it a two stage check:

request()->validate([
    'more_than' => 'required',
    'less_than' => 'required'
]);

request()->validate([
    'more_than' => 'numeric|gt:less_than',
    'less_than' => 'numeric|lt:more_than'
]);

That would be the easiest way.

Borisu's avatar

@SGUserFace what do you mean a two stage? Just write it exactly as I wrote it. It works. If any of the fields fail the first check you'll get the error immediately, else the request will be validated with the second set of rules.

Please or to participate in this conversation.