How to Connect Multiple Database in Laravel 11

Hello, laravel web developer! In this article, we'll see how to connect multiple databases in laravel 11. Here, we'll multiple database connections like MySQL, MongoDB, and PostgreSQL in laravel 11 with creating migration, model, and query examples.

The configuration for Laravel's database services is located in your application's config/database.php configuration file.

In this file, you can define all of your database connections, as well as specify which connection should be used by default.

Laravel 11 Multiple Database Connect

laravel 11 multiple database connect

 

 Set .env Variable

Set both database configurations in a .env file like the below code.

// 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=

 

Configure Database

Then, we'll open the database.php file and add a new connection key as below.

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

.....   

 

Multiple Database Connections with Migration

Next, we'll create migrations for multiple database connections.

Default:

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

Second Database: 

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

 

Multiple Database Connections with the Model

Then, we'll use multiple database connections in the model.

Default:

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class User extends Model
{
    use HasFactory;
   
    protected $fillable = [
        'name', 'email'
    ];
}

Second database:

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class User extends Model
{
    use HasFactory;
  
    protected $connection = 'mysql2';
  
    protected $fillable = [
        'name', 'email'
    ];
}

 

Multiple Database Connections in the Controller

Default:

class UsersController extends BaseController
{
    public function getRecord()
    {
        $users = Users::get();
        return $find;
    }
}

Second database:

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

 

Getting Data from Multiple Databases Using DB

Default:

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

Second database:

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

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS