Home » , , » How To Create A Multiple DataBase Connections In Laravel

How To Create A Multiple DataBase Connections In Laravel

Written By Unknown on September 08, 2014 | Monday, September 08, 2014

A while ago, I answered on this SO question about using 2 database connections.
In answering that, I did some investigation which I'll write up here.

Here is how to run more than one database connection.

This article is about using databases with different data, not necessary for load balancing (or connection pooling) between databases.

Define Connections

Inside of your datbase configuration file - likely app/config/database.php - you can define more than one database connection of any type. In fact, you can define as many connections as you'd like. For instance, if your application has to pull data from 2 MySQL databases, you can define them both separately:

<?php return array(
'default' => 'mysql', 'connections' => array( # Our primary database connection 'mysql' => array(
'driver' => 'mysql', 'host' => 'host1',
'database' => 'database1',
'username' => 'user1',
'password' => 'pass1'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
# Our secondary database connection
'mysql2' => array(
'driver' => 'mysql',
'host' => 'host2', 'database' => 'database2', 'username' => 'user2', 'password' => 'pass2'
'charset' => 'utf8', 'collation' => 'utf8_unicode_ci',
'prefix' => '', ),
), );

We have our default connection still set to mysql. This means that, unless we specify otherwise, the application will use thet mysql connection.

Specify Connection

Now that we have a 2nd database connection setup - how do we use it in code?
It turns out there's a few ways!

Schema

Within the Schema Builder, you can use the Schema facade with any connection. To specify which connection to use, simply run the connection() method:

Schema::connection('mysql2')->create('some_table', function($table) {
$table->increments('id'):
});

Query

Similar to Schema Builder, you can define a connection on the Query Builder:
$users = DB::connection('mysql2')->select(...);

Eloquent

You can also define which connection to use in your Eloquent models as well!
One way is to set the $connection variable in your model:
<?php class SomeModel extends Eloquent { protected $connection = 'mysql2'; }

You can also define the connection at runtime via the setConnection method.

<?php
class SomeController extends BaseController
{
public function someMethod() { $someModel = new SomeModel; $someModel->setConnection('mysql2'); $something = $someModel->find(1);
return $something;
}
}
Be careful about attempting to build relationships with tables across databases! It is possible to do, but it can come with some caveats and depends on what database and/or database settings you have.

0 comments:

Post a Comment