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 Upload image with preview in Laravel 9 with example

How to Upload image with preview in Laravel 9 with example ?

May 14, 2022May 14, 2022

Upload image with preview in laravel or for any website can be basic requirement like set up a profile picture to providing the documents. Laravel 9 provides robust functionality to upload and process the image with security. Laravel simply use Request file method to access the uploaded file and then…

Read More
Php How to Add or Update Index in Laravel Migration

How to Add or Update Index in Laravel Migration?

August 21, 2022March 16, 2024

Add or Update Index in Laravel Migration can be implement easily using the migrations libraries index method. Migrations provides almost all feature to create the database schema and create and update index in laravel migration. As We know database index is used to improve the speed of tables. Index can…

Read More
Php upload file in php

How to upload file in php ?

September 13, 2021September 29, 2021

In this tutorial, we will learn basic of uploading of a file in php and also basic configuration required for php file upload. Configure the php.ini for large file upload By default php support 2 mb of file upload but in real world we require more than 2 mb. Same…

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

  • 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

  • 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
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version