How to Use Multiple Databases in Laravel

Published on December 21, 2021 49 sec read

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.

'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,

Update .env File

Put the below code in .env file


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.

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

That’s it. That’s all for today. Thanks for reading 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.