Search

How to use Multiple Databases in Laravel

post-title

You already know how to connect MySQL database with Laravel application. But sometimes, you might need to use multiple databases with single Laravel application. Or you might needed to synchronize data from another server database.

In this article, we will learn about how to connect Laravel application with second database. We will also learn how to connect specific Model and Migration with second connection instead of default database.

If you see your .env file, you already have default database connection details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_one
DB_USERNAME=root
DB_PASSWORD=secret

Now copy these lines and create new credential details for second database. If the second database is in remove server, then use remote server IP.

DB_CONNECTION_SECOND=mysql
DB_HOST_SECOND=110.72.248.93
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=db_two
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=secret

Sameway, also copy and add second database array to connections array in config/database.php file.

'connections' => [

    'mysql' => [
        'driver'    => env('DB_CONNECTION'),
        'host'      => env('DB_HOST'),
        'port'      => env('DB_PORT'),
        'database'  => env('DB_DATABASE'),
        'username'  => env('DB_USERNAME'),
        'password'  => env('DB_PASSWORD'),
    ],

    'mysql_second' => [
        'driver'    => env('DB_CONNECTION_SECOND'),
        'host'      => env('DB_HOST_SECOND'),
        'port'      => env('DB_PORT_SECOND'),
        'database'  => env('DB_DATABASE_SECOND'),
        'username'  => env('DB_USERNAME_SECOND'),
        'password'  => env('DB_PASSWORD_SECOND'),
    ],
],

Now you have created and connected second database with Laravel application. When you want to query in second database from controller class, add connection() method to query.

$transactions = DB::connection('mysql_second')
    ->table('transactions')
    ->where('status', 'success')
    ->get();

If you want to use Eloquent query on second database, use on() method before query.

$transactions = Transaction::on('mysql_second')
    ->where('status', 'success')
    ->get();

And if specific table is mostly uses second database, you can bind model with specific connection. This way, you don't need to pass on() method for every query.

<?php

class Transaction extends Model
{
    protected $connection = 'mysql_second';
    // ...
}

This way you can use multiple databases to single Laravel application. I hope this will help you on your work.