Using The Where Clause in Validation Rules

Arie Visser • December 20, 2019

laravel php validation

Just recently I discovered you can apply where statements to the unique and exists validation rules in Laravel, without using a closure.

This means you can refactor this:

// Name has to be unique for users from the same country
'name' => [
    'required`,
    Rule::unique('users')->where(function ($query) {
        return $query->where('country_id', $countryId);
    }),
];

to this:

// Name has to be unique for users from the same country
'name' => [
    'required`,
    Rule::unique('users')->where('country_id', $countryId),
];

It also works when you need multiple where statements, and with the exists rule:

// At least one user from the same country and department already has this role
'role' => [
    'required`,
    Rule::exists('users')
        ->where('country_id', $countryId)
        ->where('department_id', $departmentId),         
];

The advantages are the readability of the code, and the effect that you don't have to import variables from the parent scope with a use statement (except when you use short closures, in that case you don't have to import variables from the parent scope).

A closure can be used when you need a query that has combined statements, such as andWhere and orWhere.

Other statements that you can use in the same way, besides where, are: - whereNot - whereNull - whereNotNull - whereIn - whereNotIn

The complete characteristics of these database rules can be found in the Illuminate\Validation\Rules\DatabaseRule trait.