How to use multiple databases in Laravel

How to use multiple databases in Laravel

You can use multiple databases in laravel using it’s model structure. Lets understand it by an example.

  • database_1
  • database_2

Laravel has inbuilt support for multiple database systems, you need to provide connection details in config/database.php file.

return [
    'default' => env('DB_CONNECTION', 'mysql'),

    'connections' => [
        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            .

            .
        ],
      'mysql2' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST_2', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE_2', 'forge'),
            'username' => env('DB_USERNAME_2', 'forge'),
            'password' => env('DB_PASSWORD_2', ''),
            .

            .
        ],
];

Define DB_DATABASE, DB_USERNAME, DB_PASSWORD, DB_DATABASE_2, DB_USERNAME_2, DB_PASSWORD_2 env parameters as per your details.

After this create your models and define different connection.

//Model.php
protected $connection = 'mysql';

//Model2.php
protected $connection = 'mysql2';

That’s it.