Laravel Notes

Laravel Notes

How to use Multiple databases in Laravel

How to use Multiple databases in Laravel

Vineeth Vijayan's photo
Vineeth Vijayan
·Jan 11, 2022·

2 min read

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".



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)

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.

Share this