Home > Back-end >  Laravel validating the uniqueness of a field only when the value is not null
Laravel validating the uniqueness of a field only when the value is not null

Time:03-10

I have a system_name field that is nullable that I want to validate for uniqueness if the input is not null.

As based on the recommended solutions given by others, it can just be

$this->validate($request, [
    'system_name' => 'nullable|unique:systems'
]);

Why is it that this solution work? Given that when a null value is entered for system_name, shouldn't it pass the nullable rule but fail the unique rule as the null value is not unique since it has been used before?

Can I also enquire what is the difference between encapsulating the rule with '' vs [ ] ? As shown by the validation done on username and email

public function rules()
{
    return [
            'username' => 'required|min:8',
            'email' => ['required', Rule::unique('users')]
        ];
}

CodePudding user response:

The documentation for the nullable rule simply states:

The field under validation may be null.

What it doesn't state that if the field is null, the subsequent validation is ignored. So in your case, the unique:systems rule is not called. And from a logical standpoint, this makes sense, as a nullable column/index should not treat null as a unique value.1

Additionally, the difference between 'nullable|unique:systems' and ['nullable', 'unique:systems'] (or other variants) is: nothing, really. In older versions of Laravel, the 'rule1|rule2' syntax was the only method available. Compare the documentation for Laravel 5.4 and Laravel 6.x:

https://laravel.com/docs/5.4/validation#basic-usage https://laravel.com/docs/6.x/validation#basic-usage

The 6.x version includes:

Alternatively, validation rules may be specified as arrays of rules instead of a single | delimited string

Nowadays, both syntaxes are acceptable, mainly to support older versions for backwards compatibility, and syntax preference. I like the | delimited string, but the [] method is a bit more flexible (since you can use Rules and Functions as shown in some of the examples in the Documentation.)


1 Typically; that might not be true for all DB types, but from my experience this is the case.

  • Related