W3docs

How to use multiple databases in Laravel

Using multiple databases in Laravel is quite easy.

Using multiple databases in Laravel is quite easy. First, you will need to configure your database connections in the config/database.php file. You can add as many connections as you like to this file.

Once you have configured your database connections, you can use the DB::connection() method to specify which connection you want to use. For example, if you have a connection named mysql and you want to run a query on that connection, you can use the following code:

How to use multiple databases in Laravel?

$users = DB::connection('mysql')->select('select * from users');

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

You can also set the default connection that Laravel should use in the config/database.php file by setting the value of the default option.

Example of setting the default connection that Laravel should use

'default' => 'mysql',

Once you have set the default connection, you can use the DB facade as usual to run queries without having to specify the connection each time.

Example of using the DB facade to run queries in Laravel

$users = DB::select('select * from users');

To assign a specific database connection to an Eloquent model, set the $connection property on the model class:

class SecondaryUser extends \Illuminate\Database\Eloquent\Model
{
    protected $connection = 'mysql_secondary';
}

For read/write replicas or secondary connections, you can define them directly in the connections array within config/database.php:

'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', ''),
    'read' => [
        'host' => env('DB_READ_HOST', '127.0.0.1'),
    ],
    'write' => [
        'host' => env('DB_WRITE_HOST', '127.0.0.1'),
    ],
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
    'engine' => null,
],

I hope that helps! Let me know if you have any other questions.