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

Laravel Clear cache in laravel

How to Clear cache in Laravel 8 ?

October 15, 2021October 15, 2021

Cache is used to improve the performance of web application using caching the views templates, queries, CSS, JavaScript etc. Cache improves the performance by serving the cached pages and improves the speed of website but sometime develops face issues like they change something in Laravel application but it does not…

Read More

How many type of methods in Restful api?

August 28, 2021February 22, 2024

Restful api is very useful today while creating a mobile application or web application. Restful api or Http request methods There is 4 types of method of http request. Post Get Put Delete Patch 1. Post method Post method is widely used to fetch the content of a form or…

Read More
Php File Validation in laravel 8

How to use file validation in Laravel 8 with example

November 27, 2021January 26, 2022

Laravel provides multiple ways to validate a form or a file in form with it’s own validation library. In this tutorial we will learn about the image validation for specific extension and file size. In this tutorial i will use a simple form and a file input field to validate…

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

  • 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

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version