Laravel 8 Multiple Database Connections

Websolutionstuff | Apr-19-2021 | Categories : Laravel MySQL

Hello Freinds,

In this tutorial we will see laravel 8 multiple database connections. Today I will give you step by step implementation of how to use laravel 8 multiple database connections.

Many times we have requirment in our project to use multiple database connection like MySQL, MongoDB, PostgreSQL etc. When you work with very large amount of project then you will need to manage multiple database connection. So, in this tutorial we will see one or more database connection in single laravel application .

So let's follow below steps for laravel 8 multiple database connection.

 

Set .env Variable For Laravel 8 Multiple Database Connections

 

// Database 1

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_1
DB_USERNAME=root
DB_PASSWORD=

// Database 2

DB_CONNECTION_SECOND=mysql
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=database_2
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=

 

 

Use .env Variable : 

Now, as we created variable in .env file we need to use that variable on config file. so let's open database.php file and add new connections key as like bellow:

config/database.php

<?php

use Illuminate\Support\Str;

return [

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

    'connections' => [

        .....   

        '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' => env('DB_CONNECTION_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' => '',
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
        ],

.....   

 

post_details_addscode

 

Use Multiple Database Connections :

Here, I will give you simple example of how to use as multiple connection with migration.

Default Database :

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email');
        $table->timestamps();
    });
}

 

Second Database : 

public function up()
{
    Schema::connection('mysql2')->create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email');
        $table->timestamps();
    });
}

 

 

Use Multiple Database Connection with Model

In this step we will see multi database with model.

Default :

<?php

namespace App;
  
use Illuminate\Database\Eloquent\Model;
   
class Users extends Model
{
  ....
}

 

Second :

<?php

namespace App;
  
use Illuminate\Database\Eloquent\Model;
   
class Users extends Model
{
    protected $connection = 'mysql2';
    ...
}

 

Use Multiple Database Connection in Controller

Default :

class UsersController extends BaseController
{
    public function getRecord()
    {
        $users = new Users;
        $find = $users->find(1);
        return $find;
    }
}

 

Second :

class UsersController extends BaseController
{
    public function getRecord()
    {
        $users = new Users;
        $users->setConnection('mysql2');
        $find = $users->find(1);
        return $find;
    }
}

 

Use Multiple Database Connection with Query Builder

Default :

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

 

Second :

$users = DB::connection('mysql2')->table("users")->get();
print_r($users);

 

Recommended Post
Featured Post
Razorpay Payment Gateway Integration in Laravel 10 and VueJS 3
Razorpay Payment Gateway Integ...

In the rapidly advancing world of technology, the combination of Laravel 10 and VueJS 3 is unparalleled and exceptionall...

Read More

Aug-30-2023

Date Range Filter In Datatable jQuery Example
Date Range Filter In Datatable...

In this article, we will see the date range filter in the datatable jquery example. Many times we required data of ...

Read More

Nov-14-2022

How To Avoid TokenMismatchException On Logout
How To Avoid TokenMismatchExce...

Many times we faced a Tokenmismatch error in laravel. This error occurs If you stay too long time on one form...

Read More

Jun-29-2020

Laravel 9 Autocomplete Search from Database
Laravel 9 Autocomplete Search...

In this article, we will see laravel 9 autocomplete search from the database. Using ajax autocomplete textbox in la...

Read More

Mar-14-2022