Laravel Validation unique/exists with different database connection

user3130415 picture user3130415 · Sep 23, 2015 · Viewed 11k times · Source

In the documentation, I saw you could set a connection for the unique rule which is great. However, the exists doesn't seem to follow the same logic. Take this for example:

$rules = [
    'username'         => 'required|max:40|unique:user',
    'name'             => 'sometimes|required',
    'email'            => 'required|email|max:255|unique:int.user',
    'password'         => 'sometimes|required|confirmed|min:6',
    'password_current' => 'sometimes|required'
];

The unique rule works GREAT in this instance. It uses my database connection called 'int' and calls the user table. HOWEVER, when the rules are reversed like so:

$rules['email'] = 'required|email|max:255|exists:int.user';

I got this error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'int.user' doesn't exist (SQL: select count(*) as aggregate from int.user where email = [email protected])

It's trying to call an int.user table instead of using the int database connection.

Is there a reason exists doesn't act the same way as unique? Thanks.

Answer

Omar Faruk picture Omar Faruk · Dec 22, 2016

instead of using connection name you can try with straight Database name which is defined in "int" connection. faced similar problem and these way worked for me. like

$rules['email'] = 'required|email|max:255|exists:DB_Name.user';