Laravel Connect Multiple Databases in Same Project

Last modified on April 22, 2019 50 sec read

HIRE US 🖐
We're available to do freelance project. Take a look at our services!

We can easily connect to multiple databases in the same project. Let’s follow these simple steps:

Table of Contents

  1. Update .env File
  2. Configure database.php
  3. Connect to New Database

Step 1 : Update .env File

Open .env file from your project. Make some env variables for new database. Have a look at the example:

.env
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=database1
DB_USERNAME=root
DB_PASSWORD=pass

DB_HOST_SECOND=localhost
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=database2
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=pass

Step 2 : Configure database.php

Now we have to configure the database.php. Open database .php from config/database.php and duplicate the present mysql array & renamed to mysql_second. See this example:

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

'mysql_second' => [
    'driver'    => 'mysql',
    'host'      => env('DB_HOST_SECOND'),
    'port'      => env('DB_PORT_SECOND'),
    'database'  => env('DB_DATABASE_SECOND'),
    'username'  => env('DB_USERNAME_SECOND'),
    'password'  => env('DB_PASSWORD_SECOND'),
    ------------
],

Step 3 : Connect to New Database

We have completed all configuration tasks. Let’s connect to new database.

TestDBController.php
class TestDBController extends Controller
{

    public function index()
    {
        $db_ext = \DB::connection('mysql_second');
        $users= $db_ext->table('users')->get();
        print_r($users);
    }

}
We are done. I hope this article will help you.

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.
Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

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