How To Configure Multiple Database Connections In Laravel 11

Configuring multiple database connections in Laravel allows you to efficiently manage and interact with different databases within a single application. Laravel makes this process straightforward by providing a clean and intuitive configuration system. Here’s how you can configure multiple database connections in Laravel:

  1. Database Configuration File:
    Laravel’s database configuration is stored in the config/database.php file. Open this file to define your database connections.
  2. Define Connection Arrays:
    To configure multiple database connections, you need to define an array of connection settings. Each connection should have a unique key. In this example, let’s configure two database connections: mysql and pgsql.
'connections' => [

    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', '127.0.0.1'),
        '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,
    ],

    'pgsql' => [
        'driver'   => 'pgsql',
        'host'     => env('DB_PG_HOST', '127.0.0.1'),
        'port'     => env('DB_PG_PORT', '5432'),
        'database' => env('DB_PG_DATABASE', 'forge'),
        'username' => env('DB_PG_USERNAME', 'forge'),
        'password' => env('DB_PG_PASSWORD', ''),
        'charset'  => 'utf8',
        'prefix'   => '',
        'schema'   => 'public',
    ],

],
  1. Environment Configuration:
    Next, set the environment variables in the .env file for each database connection.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_mysql_database
DB_USERNAME=your_mysql_username
DB_PASSWORD=your_mysql_password

DB_PG_CONNECTION=pgsql
DB_PG_HOST=127.0.0.1
DB_PG_PORT=5432
DB_PG_DATABASE=your_pgsql_database
DB_PG_USERNAME=your_pgsql_username
DB_PG_PASSWORD=your_pgsql_password
  1. Usage:
    You can then use these connections by referencing their keys in your Eloquent models or queries.
// Using default connection (mysql)
$users = App\User::all();

// Using pgsql connection
$records = DB::connection('pgsql')->select(...);

By following these steps, you can easily configure and utilize multiple database connections in your Laravel application.

Leave a Reply