Wednesday, February 13, 2019

Laravel - Connect With Multiple Database

Hello,

In this blog post I am going to mention how we can connect multiple databases with Laravel applications. First add multiple connections in config/database.php For this copy paste mysql connection and change configurations as following.

'mysql1' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE_1',''),
            'username' => env('DB_DATABASE_1_USERNAME',''),
            'password' => env('DB_DATABASE_1_PASSWORD',''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],

Now add these values in .env file

DB_DATABASE_1=YOUR_DB_NAME
DB_DATABASE_1_USERNAME =YOUR_USER_NAME
DB_DATABASE_1_PASSWORD = YOUR_PASSWORD

Now laravel give you two ways to switch database connection.

1) Set connection property in Eloquent Model

protected $connection = 'mysql1';

So here when you use this model to get data it will use the connection specified in the mysql1. You don't need to manually change it. 

2) use DB:connection 

If you are using raw queries and using DB facade so to get query the data. You have to use following logic.

DB::connection('mysql1')->table(env('DB_DATABASE_1','')).'.TABLE_NAME')


So here first you have specified connection and then used table by appending db name in front of it. 

So this is how you can manage multiple databases.


No comments:

Post a Comment