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!
+1
I think this is a real great article. Much thanks again. Fantastic.
Thanks for the article.Really thank you! Awesome.