How to use multiple database in Laravel

There are some cases where we need to imlement a multiple databases in our application. In Laravel we can achieve this very efficiently.

Step 1 : Update Database file

The first thing we need to do is a change in our config/database.php file like below.

//This Code already exists in a file

'mysql' => [
    'driver'    => env('DB_CONNECTION'),
    'host'      => env('DB_HOST'),
    'port'      => env('DB_PORT'),
    'database'  => env('DB_DATABASE'),
    'username'  => env('DB_USERNAME'),
    'password'  => env('DB_PASSWORD'),
],

//This code we need to add in a file

'mysql2' => [
    'driver'    => env('DB_CONNECTION2'),
    'host'      => env('DB_HOST2'),
    'port'      => env('DB_PORT2'),
    'database'  => env('DB_DATABASE2'),
    'username'  => env('DB_USERNAME2'),
    'password'  => env('DB_PASSWORD2'),
],

Step 2: Update .env file

We have used env parameter in a config file so our next step would be to add parameters for second connection in .env file

//This Code already exists in a file

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE={DATABASENAME}
DB_USERNAME={USERNAME}
DB_PASSWORD={PASSWORD}

//This code we need to add in a file

DB_CONNECTION2=mysql
DB_HOST2=127.0.0.1
DB_PORT2=3306
DB_DATABASE2={DATABASENAME}
DB_USERNAME2={USERNAME}
DB_PASSWORD2={PASSWORD}

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *