How to Connect Multiple Database in Laravel 11: A Comprehensive Guide

In this article, we’ll show you how to connect multiple databases in Laravel 11. We’ll cover how to set up connections for MySQL, MongoDB, and PostgreSQL, and provide examples for creating migrations, models, and queries.

Laravel is a popular PHP framework that makes web development easier with its elegant features. One of these features is the ability to connect to multiple databases. This can be useful when you need to handle different types of data, such as user data, product data, or analytics data. In this guide, we’ll walk you through the steps to set up multiple database connections in Laravel, with practical examples.

The configuration for Laravel’s database connections is found in the config/database.php file. In this file, you can define your database connections and specify which one should be used by default.

Step 1: Connect Multiple Databases in Laravel 11

Set .env Variables

First, add the database configurations to your .env file as shown below:


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

Next, open the config/database.php file and add a new connection key like this:


use Illuminate\Support\Str;

return [

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

    'connections' => [

        // Default MySQL connection
        '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'),
            ]) : [],
        ],

        // Second MySQL connection
        '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,
        ],

    ],
Creating Migrations for Multiple Databases

Now, let’s create migrations for each database:

Default Database:


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();
    });
}
Using Multiple Database Connections in Models

Here’s how to specify which connection a model should use:

Default Database:


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:


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'
    ];
}
Using Multiple Database Connections in Controllers

Here’s how to access different databases in a controller:

Default Database:


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 Facade

Here’s how to get data from each database:

Default Database:


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

Second Database:


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

For more details, you can check the Laravel Documentation

You may also find interesting:

How to avoid TokenMismatchException on logout

Post a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *