How to use Multiple Databases in Laravel?

Sometimes we need two or more databases for the same Laravel project, So we can easily connect our Laravel Application with external data from another database

Step: 1 Update config/database.php

In config/database.php Here we can see an array of all connections like MySQL, PostgreSQL, SQL Server. Here we can add more than one connection with the same database system.

In this post, we will be using MySQL. So, let’s copy a default array item and paste as another one underneath – and call it mysql_external

config/database.php

'connections' => [

        'sqlite' => [
        	// ...
        ],

        'mysql' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST', 'localhost'),
            'database'  => env('DB_DATABASE', 'forge'),
            'username'  => env('DB_USERNAME', 'forge'),
            'password'  => env('DB_PASSWORD', ''),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],

        'mysql_external' => [
            'driver'    => 'mysql',
            'host'      => env('DB_EXT_HOST', 'localhost'),
            'database'  => env('DB_EXT_DATABASE', 'forge'),
            'username'  => env('DB_EXT_USERNAME', 'forge'),
            'password'  => env('DB_EXT_PASSWORD', ''),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],

        'pgsql' => [
        	// ...
        ],

        'sqlsrv' => [
        	// ...
        ],

    ],

Step: 2 Update .env file

Now In the second step, we have two options: provide those external credentials here in the same config/database.php file, or add them into the .env file.

DB_HOST=localhost
DB_DATABASE=testing
DB_USERNAME=homestead
DB_PASSWORD=secret

DB_EXT_HOST=localhost
DB_EXT_DATABASE=testing2
DB_EXT_USERNAME=homestead
DB_EXT_PASSWORD=secret

Step: 3 Now fetch data from second database

So, we have a new connection named mysql_external which has the credentials provided, now time to use it. So in your code.

where you want to use or access data from that external database, you just call DB::connection() method and assign the result to the variable. Then we can use that variable to make any queries.

Here is an example.

class TestController extends Controller
{

    public function getTest()
    {
        $db_ext = \DB::connection('mysql_external');
        $countries = $db_ext->table('countries')->get();
        print_r($countries);
    }

}

So here we completed this post on How to use Multiple Databases in Laravel?