Multiple DB Connections in Laravel 5

Struggling to connect different database in Laravel or want to switch different DB connection dynamically? Then this article will solve your query.

Few day back while developing an application I come up to a point where I need to connect to the different database dynamically. I google around and I found few good solution in multiple websites; So I thought to stitch them into a single piece.

Before proceeding we first have to edit our database.php which is located in /config/database.php for Lavael 4.2 it is in app/config/database.php.

<?php

return [
    //…
    //…
    'default' => 'mysql_primary',
    'connections' => [
        //..
        //Our Default Database Connection
        'mysql_primary' => [
            'driver' => 'mysql',
            'host' => 'localhost',
            'database' => 'my_first_db',
            'username' => 'root',
            'password' => ",
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => ",
            'strict' => false,
        ],
        
        //Our Secondary Database Connection
        'mysql_second' => [
            'driver' => 'mysql',
            'host' => 'localhost',
            'database' => 'my_second_db',
            'username' => 'root',
            'password' => ",
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => ",
            'strict' => false,
        ],
        //..
        //…
    ],
    //..
    //…
];

Now that we have set the DB connections it's time to use it

Defining in Model

If have Model which uses a different database then we can define it at the model level like this:

<?php

class MyModel extends Eloquent {

//…
protected $connection = 'mysql_second';

//…
//…
}

In Eloquent Query

<?php

//create an instance of your model
$objMyModel = new MyModel();
//query for fetching data
$data = $objMyModel->setConnection('mysql_second')
->select('col_1')
->get();

In DB Query

<?php

//Defining a connection in Query Builder
$data = DB::connection('mysql_second')
->table('table_name')
->select('col_1')
->get();

//Defining a connection within the Schema Builder.
Schema::connection('mysql_second')->create('table_name', function($table) {
$table->increments('id');
});

Let me know through the comment if I missed out any point. Cheers!

Rana Ghosh

Rana Ghosh

I'm a PHP, MySQL, jQuery expert, and designing specialist. My elating approach of seeing web world with a different sight leaves others amazed. My skills include codeigniter, Laravel. I enjoy taking challenges.
I love to play FIFA Online 3.

Articles: 1

3 Comments

Leave a Reply to ucretsizCancel Reply

Your email address will not be published. Required fields are marked *