Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to Use Multiple Database Connection in Laravel

How to Use Multiple Database Connection in Laravel ?

Aman Jain, August 16, 2022March 16, 2024

Laravel has ability to make use database connection and can be used any of connection at runtime. In this article i will show you to use multiple database connection in laravel from different servers and then use these connection in our application during the run time according to use of them.

Laravel manages multiple connection in query builder, Eloquent model and even in run time query so we can fetch the result appropriately. We will get a clear understanding how we can achieve all these in migration, run time configuration, DB builder and Eloquent.

We will take simple examples of each of methods to understand this. All these examples will work in any version on laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9.

Sometime in our application we want different connections for storing relational data and log data like audit to store in different database storage.

Let’s quickly see how it works, first of all we will update our .env configuration file and then update the config/database.php file as follow

Create Config to Use Multiple Database Connection in Laravel

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database1
DB_USERNAME=root
DB_PASSWORD=password
   
DB_CONNECTION_SECOND=mysql
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=database2
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=password

Here we created another env constant DB_CONNECTION_SECOND and so on so we can use them in config/database.php as follow

 'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            'url' => env('DATABASE_URL'),
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
            'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
        ],

        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_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'),
            ]) : [],
        ],
        'mysql2' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL_SECOND'),
            'host' => env('DB_HOST_SECOND', '127.0.0.1'),
            'port' => env('DB_PORT_SECOND', '3306'),
            'database' => env('DB_DATABASE_SECOND', 'forge'),
            'username' => env('DB_USERNAME_SECOND', 'forge'),
            'password' => env('DB_PASSWORD_SECOND', ''),
            'unix_socket' => env('DB_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'),
            ]) : [],
        ],

Here we created a new connection mysql2 which we can connect to another database

'mysql2' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL_SECOND'),
            'host' => env('DB_HOST_SECOND', '127.0.0.1'),
            'port' => env('DB_PORT_SECOND', '3306'),
            'database' => env('DB_DATABASE_SECOND', 'forge'),
            'username' => env('DB_USERNAME_SECOND', 'forge'),
            'password' => env('DB_PASSWORD_SECOND', ''),
            'unix_socket' => env('DB_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'),
            ]) : [],
        ],

Use Multiple Database in Laravel

Next, we have created config and connection details in config successfully. now we will see to use these connection using multiple ways and methods in migration, model, controller, db query builder and controller itself.

Use Multiple Database Connection in Model

Sometimes we want some model dedicatedly for a specific connection so that we can query all the queries in that database connection only so to do that we need to define $connection property to model as follow

<?php
  
namespace App;
  
use Illuminate\Database\Eloquent\Model;
   
class Article extends Model
{
    protected $connection = 'mysql2';
}

So we defined protected $connection = 'mysql2'; to for this model article so all queries will point to mysql2 connection.

Read Also : How to make database connection in Laravel 8 ?

Use Multiple Database Connection in Migration

In this method we will use other database connection mysql2 in migration so below is the code

<?php
.....
public function up()
{
    Schema::connection('mysql2')->create('articles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('body')->nullable();
        $table->timestamps();
    });
}

So we defined Schema::connection('mysql2'); to use mysql2 connection.

Use Multiple Database Connection in DB builder

Sometimes we want run query using query builder so we can use as follow

DB::connection('mysql2')->table("articles")->get();

Use Multiple Database Connection in Controller run time

There can be many conditions where we want to use multiple connection in our controller or model logic layer we want connection on demand so we can easily set connection using $Model->setConnection('mysql2'); and complete example is here

<?php
  
class ArticleController extends BaseController
{
    public function get()
    {
        $Model = new Article;
        $Model->setConnection('mysql2');
        $find = $Model->find(1);
        return $find;
    }
}

Related

Php Laravel Laravel 10 Laravel 9 connectiondatabaselaravelmultiple

Post navigation

Previous post
Next post

Related Posts

Php How to set timezone dynamically and globally in Laravel

How to set timezone dynamically and globally in Laravel ?

September 20, 2022March 16, 2024

Laravel stores timezone configurations in config/app.php file and we can easily set timezone dynamically and globally in Laravel. Laravel usage carbon library to get the current date time and format, carbon also respects the timezone defined in config/app.php file. After php 5, php also introduced DateTime class to conduct the…

Read More
Php How to Create Zip of File or Folder in Laravel

How to Create Zip of File or Nested Folder in Laravel ?

May 22, 2022May 24, 2022

Zip files are used to create lossless data compression and store multiple files folder in single file. In laravel create zip of file or nested folder laravel can be archived by ZipArchive library,its gives easy to use flexibilities to developers so they can easily integrate the Zip creation activity in…

Read More
Softwares Traits-in-Php

What is a traits in PHP and how to use it ?

June 20, 2021November 8, 2023

Before PHP 5.4, there was no way to implement multiple inheritance in PHP then PHP 5.4 introduce traits as a substitute of multiple inheritance in PHP. By using the traits PHP solve the problem of Multiple Inheritance. A class only extend one class what if we wanted to use multiple…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Mastering Schedule Management with Laravel Zap
  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version