How to use Multiple Databases In Laravel

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryLaravel

In this tutorial we will learn how to use multiple databases in laravel.

 

How to use Multiple Databases In Laravel

Laravel provides an easy and efficient way to work with multiple databases in a single application. Here are the steps to use multiple databases in Laravel:

 

Step 1 - Define database connections in the configuration file

Open the database configuration file located at config/database.php and add another database connection array with a unique name and credentials.

'connections' => [

    'mysql' => [
        'driver' => 'mysql',
        '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', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

    'mysql2' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST_SECONDARY', '127.0.0.1'),
        'port' => env('DB_PORT_SECONDARY', '3306'),
        'database' => env('DB_DATABASE_SECONDARY', 'forge'),
        'username' => env('DB_USERNAME_SECONDARY', 'forge'),
        'password' => env('DB_PASSWORD_SECONDARY', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],
],

 

Step 2 - Define environment variables

Define the environment variables for each database connection in the `.env` file.

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

DB_CONNECTION_SECONDARY=mysql2
DB_HOST_SECONDARY=127.0.0.1
DB_PORT_SECONDARY=3306
DB_DATABASE_SECONDARY=database_name
DB_USERNAME_SECONDARY=root
DB_PASSWORD_SECONDARY=

 

Step 3 - Use the Connection You can now use the second database connection by specifying the connection name in the model or query builder:

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

If you want to use a different connection for an Eloquent model, you can specify the connection property in the model class:

class User extends Model
{
    protected $connection = 'mysql2';
}

 

That's it! You can now use multiple databases in Laravel.

Comments 0

Leave a comment