Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel validation 'different' fails when other attribute is null

Hello I'm having troubles with the different validation.

I have 2 variables that can be null. What I want to achieve is whenever the variable is present, force it to have exactly 5 digits and not to have the same value.

These are the rules that I've set:

'zip_departure' => 'nullable|digits:5',
'zip_arrival' => 'nullable|different:zip_departure|digits:5',

The problem is when I set zip_departure as null it throws up a validation error saying both parameters cannot have the same value. But if I dd() both variables they have:

'zip_departure': null
'zip_arrival': '28100'

What am I missing here?

I'm using Laravel 5.6

like image 205
Alberto Avatar asked Oct 21 '25 15:10

Alberto


1 Answers

As of Laravel 5.6 the validator explicitly checks whether the other value is not null.

public function validateDifferent($attribute, $value, $parameters) 
{ 
    $this->requireParameterCount(1, $parameters, 'different'); 

    foreach ($parameters as $parameter) { 
        $other = Arr::get($this->data, $parameter); 

        if (is_null($other) || $value === $other) { 
            return false; 
        } 
    }
}

framework/src/Illuminate/Validation/Concerns/ValidatesAttributes.php:432

That's why different:var2 works but different:var1 doesn't.


As of Lravel 5.8 and higher this is fixed

like image 187
Max Flex Avatar answered Oct 25 '25 04:10

Max Flex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!