How to use Multiple databases in Laravel

How to use Multiple databases in Laravel

Usually each website only need a single database. A single database can satisfy all requirements of the website. But there many be circumstances were we need more than one database. For example, lets say the developer decides to use a different database for writing tests in the application. Lets see how can he do that.

First he will edit the .env file to include details of his second database which he prefers to name as "test_office_database".

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=office_database
DB_USERNAME=root
DB_PASSWORD=secret

TEST_DB_CONNECTION=test_mysql
TEST_DB_HOST=127.0.0.1
TEST_DB_PORT=3306
TEST_DB_DATABASE=test_office_database
TEST_DB_USERNAME=root
TEST_DB_PASSWORD=secret

Now he have the database details of two databases, next step is to edit config\database.php file to add new connection in the connections array.

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'office_database'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', 'secret'),
],
'test_mysql' => [
            'driver' => 'mysql',
            'host' => env('TEST_DB_HOST', 'localhost'),
            'port' => env('TEST_DB_PORT', '3306'),
            'database' => env('TEST_DB_DATABASE', 'test_office_database'),
            'username' => env('TEST_DB_USERNAME', 'root'),
            'password' => env('TEST_DB_PASSWORD', 'secret'),
],

So we have added the new connection to the connections array. Now lets looks at how to use this new mysql connection.

How to use this new database connection in migration?

You only need to mention the new connection name with connection method under Schema class as shown below:

Schema::connection('test_mysql')->create('customers', function($table)
{
    $table->increments('id'):
});

How to use the new database in query builder?

$customers = DB::connection('test_mysql')->table('customers')->get();

How to use the new database in eloquent?

class Customer extends Eloquent {
    protected $connection = 'test_mysql';
}

Thats it. I hope you got an idea on how to use multiple database in Laravel.

Happy Coding.