Provide custom database connection on Laravel Validator

0
4760
Laravel Framework
Laravel Framework

When using multiple databases on Laravel application, please be aware that the Validator will validate using default connection specified in config/database.phpfile.


'default' => env('DB_CONNECTION', 'default_connection_db'),

So what if you need to validate requests for data from different database connections? It’s easy, you just need to provide the connection name right before the name of table name in validation rules.

For example, if you want to validate for unique user on other_connection_db, this is how to write it:


return Validator::make($data, [
    'name' => 'required|string|max:255',
    'email' => 'required|string|email|max:255|unique:other_connection_db.users',
    'password' => 'required|string|min:6|confirmed',
]);

Look at the database connection name on unique validation rule, by doing that, Laravel will automatically validates users table on database configured in other_connection_db.

If you want to use default database connection, just omit the connection field.

This tip is noted on Laravel documentation, refer to it if you want to read more about validation.