Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Validation unique/exists with different database connection

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.

like image 543
user3130415 Avatar asked Sep 22 '15 22:09

user3130415


2 Answers

You can use

'email'           => 'exists:mysql2.users|required'

Where mysql2 is second database settings array in the database.php file

like image 78
Daud khan Avatar answered Nov 12 '22 14:11

Daud khan


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';
like image 21
Omar Faruk Avatar answered Nov 12 '22 14:11

Omar Faruk