Laravel Validation - Check Active Duplicate Emails

Viewed 6766

The table structure:

users: id  - email - active

I want check duplicated email only when active is 0.

For all emails,I do this:

'email' => 'required|unique:users|email',

Is it possible to define a condition in the validation?

2 Answers

What about using validator closure ?

public function store(Request $request)
{
   $this->validate($request, [
       'email' => [
           'required',
           'email',
           function ($attribute, $value, $fail) {
               if (Users::whereEmail($value)->whereActive(0)->count() > 0) {
                   $fail($attribute.' is already used.');
               }
           },
       ]);
   }
}

The unique rule has the following parameters:

table[,column[,ignore value[,ignore column[,where column,where value]...]]]

So something like this will work without the overhead of a closure or other custom rule. (I use the array format because it's easier to read, friendlier for VCS, and Laravel just splits the string anyway.)

'email' => [
   'required',
   'email',
   'unique:users,email,null,null,active,0',
],

I set the ignore column and value to null as nothing was getting ignored in your original question. However, if you're doing this validation on update as well as create, you'll want to ignore the ID of the user you're updating.

Related