Laravel 5.6: The values under comparison must be of the same type

342 views Asked by At

We recently upgaded Laravel from 5.5 to 5.6 I have validation rules:

return [
            'min_price' => ['numeric', 'nullable', 'min:0'],
            'max_price' => ['numeric', 'nullable', 'min:0', 'gt:min_price'],
]

It throws an error in case if

  1. min_price = null, max_price = 100
  2. min_price = 0, max_price = 99.99
  3. min_price = 12.50, max_price = 100
  4. min_price = 12.50, max_price = null It says:
ERROR: The values under comparison must be of the same type "exception":"[object] (InvalidArgumentException(code: 0): The values under comparison must be of the same type at vendor/laravel/framework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php:1659)
[stacktrace]
#0 vendor/laravel/framework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php(849): Illuminate\\Validation\\Validator->requireSameType(12.50, 100)

It says, that both fields should have the same type, so it can't compare integer and float and can't ignore nullable fields. The issue is with methods validateGt, validateLt, validateGte, validateLte in trait ValidatesAttributes. Is there some how I can extand or override that trait?

1

There are 1 answers

0
Hevyweb On

Since there is no obvious solution, I decided to create my own validator and don't use the one that Laravel offers:

class ServiceProvider extends BaseServiceProvider
{
    public function boot()
    {
        ValidatorFacade::extend('greater_than', Validator::class.'@validateGreaterThan');
        ValidatorFacade::replacer('greater_than', function ($message, $a, $b, $parameters) {
            $attributes = trans('validation.attributes');
            $other = $parameters[0];
            $other = isset($attributes[$other]) ? $attributes[$other] : $other;

            return str_replace(':field', $other, $message);
        });
    }

    public function register()
    {
    }
}

And used it in validations rules like this

return [
            'min_price' => ['numeric', 'nullable', 'min:0'],
            'max_price' => ['numeric', 'nullable', 'min:0', 'greater_than:min_price'],
]