Laravel 10 How To Use Multiple Database Connection

Reading Time: 7 minutes
579 Views

The need to connect to several databases in sophisticated web applications frequently arises, whether for managing different types of data, isolating concerns, or optimising performance. Laravel, a powerful PHP framework, provides complete support for smoothly connecting to numerous databases.

In this article, we will walk you through the process of connecting to multiple databases in Laravel 10, giving you the knowledge and skills you need to properly manage and interact with a variety of data sources.

By the end of this course, you will be confident in your ability to connect to various databases in Laravel 10.

Read More: How To Seed JSON Data in Laravel 10 Example Tutorial

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Update .env File

The very first step to create secondary databases. To create secondary database environment variables we will use .env.

Open .env file and add details of other database as well.

//...

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_1
DB_USERNAME=root
DB_PASSWORD=root
  
//...
  
DB_CONNECTION_2=mysql
DB_HOST_2=127.0.0.1
DB_PORT_2=3306
DB_DATABASE_2=database_2
DB_USERNAME_2=root
DB_PASSWORD_2=root  
  
//...  

Here, database_1 and database_2 are two databases we have connected inside .env file.

Update Database File

Open database.php file from /config folder.

This file contains the information of connection groups.

Now, you need to use .env variables (secondary database) into it.

<?php

use Illuminate\Support\Str;

return [

    'default' => env('DB_CONNECTION', 'mysql'),

    'connections' => [

        //...
        
        // Primary database
        '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'),
            ]) : [],
        ],

        // Secondary database
        'mysql_2' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST_2', '127.0.0.1'),
            'port' => env('DB_PORT_2', '3306'),
            'database' => env('DB_DATABASE_2', 'forge'),
            'username' => env('DB_USERNAME_2', 'forge'),
            'password' => env('DB_PASSWORD_2', ''),
            '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'),
            ]) : [],
        ],
      
        //...

    ],

    //...
];

How To Use Multiple Database Connection in Migration?

When you create a migration file from artisan command, it stores inside /database/migrations folder and connected with primary database..

Read More: Laravel 10 Google Line Chart Integration Example Tutorial

To connect with multiple database to migrations, look here these examples.

Primary Database(Default)

<?php

//...

public function up(): void
{
    Schema::create('products', function (Blueprint $table) {

        $table->increments('id');
        $table->string('title');
        $table->string('description')->nullable();
        $table->timestamps();

    });

}

//...

Secondary Database

To connect migration with second database, use only Schema::connection(‘mysql_2’). Use connection method and connection name in both up() and down() methods.

<?php

//...

public function up(): void
{
    Schema::connection('mysql_2')->create('products', function (Blueprint $table) {

        $table->increments('id');
        $table->string('title');
        $table->string('description')->nullable();
        $table->timestamps();

    });

}

//...

This is all about connecting migrations with multiple databases groups.

How To Use Multiple Database Connection in Model?

When you create models using artisan command, it will be stored inside /app/Models and by default it will be connected to primary database.

To connect with multiple databases, look these examples.

Primary Database(Default)

<?php
  
namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model {
  
  //...
  
}

Secondary Database

To use secondary database in model, use $connection protected variable in Model class.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model{

    protected $connection = 'mysql_2';

}

This is all about connecting models with multiple databases groups.

Read More: How To Seed CSV Data in Laravel 10 Example Tutorial

How To Use Multiple Database Connection in Controller?

If suppose, sometimes we want to connect database at runtime then we can connect direct from controller.

Primary Database(Default)

<?php

//...
class ProductController extends BaseController
{
    public function getProducts()
    {
        $productModel = new Product;

        $find = $productModel->find(1);

        return $find;
    }
}

Secondary Database

To connect with secondary database we use setConnection() method by model object and set connect group into it.

<?php

//...

class ProductController extends BaseController
{
    public function getProducts()
    {
        $productModel = new Product;

        $productModel->setConnection('mysql_2');

        $find = $productModel->find(1);

        return $find;
    }
}

This is all about connecting controllers with multiple databases groups.

How To Use Multiple Database Connection in Query Builder?

You will see connection of query builder with primary and secondary database.

Primary Database(Default)

//...

$products = DB::table("products")->get();

print_r($products);

//...

Secondary Database

//...

$products = DB::connection('mysql_2')->table("products")->get();

print_r($products);

//...

Successfully, you can see we have seen the concept of Multiple database connection in Controllers, Model, Query Builder, etc.

That’s it.

We hope this article helped you to learn about Laravel 10 How To Connect with Multiple Database Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more