How to Use Multiple Databases in Laravel

Hello Artisans,

Sometimes we need to use multiple databases in Laravel, usually in ERP level application. So, today's topic is based on that how we can use multiple databases in our application.

Table of Contents

  1. Update config/database.php
  2. Update .env file
  3. Fetch Data from Second Database

Update config/database.php

At first, we need to modify the array in our config/database.php. So, let's put the below code in our connection[] array.

config/database.php
'mysql_external' => [
    'driver' => 'mysql',
    'url' => env('EXT_DATABASE_URL'),
    'host' => env('DB_EXT_HOST', '127.0.0.1'),
    'port' => env('DB_EXT_PORT', '3306'),
    'database' => env('DB_EXT_DATABASE', 'forge'),
    'username' => env('DB_EXT_USERNAME', 'forge'),
    'password' => env('DB_EXT_PASSWORD', ''),
    'unix_socket' => env('DB_EXT_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'prefix_indexes' => true,
    'strict' => true,
    'engine' => null,
    'options' => extension_loaded('pdo_mysql') ? array_filter([
        PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
    ]) : [],
],

Update .env File

Put the below code in .env file

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

And that's it you've completed your configuration. Now at the next step, we will see, how we can retrieve the data from our 2nd database.

Fetch Data from Second Database

In this step, we will see how we can fetch the data from 2nd database.

app/Http/Controllers/HomeController.php
public function getTest()
{
  $db_ext = DB::connection('mysql_external');
  $countries = $db_ext->table('countries')->get();
  print_r($countries);
}

That's it. That's all for today. Thanks for reading.