Config multiple database connections in Laravel

0
2835
Config multiple database connections in Laravel
Config multiple database connections in Laravel

In Laravel, you can easily configure multiple database connections for your Eloquent models and queries.

First, you need to config the database connection in config/database.php


 'default' => env('GAME_DB_CONNECTION', 'game_db'),

 'connections' => [

        'game_db' => [
            'driver' => 'mysql',
            'host' => env('GAME_DB_HOST', '127.0.0.1'),
            'port' => env('GAME_DB_PORT', '3306'),
            'database' => env('GAME_DB_DATABASE', 'forge'),
            'username' => env('GAME_DB_USERNAME', 'forge'),
            'password' => env('GAME_DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

        'log_db' => [
            'driver' => 'mysql',
            'host' => env('LOG_DB_HOST', '127.0.0.1'),
            'port' => env('LOG_DB_PORT', '3306'),
            'database' => env('LOG_DB_DATABASE', 'forge'),
            'username' => env('LOG_DB_USERNAME', 'forge'),
            'password' => env('LOG_DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

    ],

As you can see above, I have configured two database connections, and set a default one.

Next, you need to config your Eloquent model by binding it to a proper database connection. For example, I have following Eloquent model:


namespace App;

use Illuminate\Database\Eloquent\Model;

class CharacterItem extends Model
{
    protected $connection = 'game_db';

    protected $table = 'character_items';
}

The $connection variable will determine what database that Eloquent should made for this model, so we don’t have to specify connection when using Eloquent.

For using DB query, you can specify the connection via DB::connection('db_connection_name').

If connection() is omitted, Laravel will use the default DB connection specified in config file.