Multiple database connection using Illuminate/Database Eloquent ORM in CodeIgniter 3

christianleroy picture christianleroy · Jan 7, 2016 · Viewed 7.4k times · Source

I have just included Laravel's database layer Eloquent to my CodeIgniter 3 project. My problem however is that I can't connect to multiple databases using Eloquent models.

For the default DB, this is how I configured the DB:

$capsule = new Capsule;

$capsule->addConnection(array(
        'driver'    => 'mysql',
        'host'      => "localhost",
        'database'  => "employees_db",
        'username'  => "root",
        'password'  => "",
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        ));

$capsule->setAsGlobal();
$capsule->bootEloquent();

The above works well. But I have an employee table from another database. I can use it using query builder, but fails with Eloquent models.

I tried this:

$employees = new Capsule;

$employees->addConnection(array(
        'driver'    => 'mysql',
        'host'      => "host2",
        'database'  => "employees_db",
        'username'  => "user",
        'password'  => "pass",
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        ),'employees');

$employees->setAsGlobal();

Tried setting up an Eloquent model and using the connection like:

protected $connection = "employees";

Is it possible to connect to multiple databases using Illuminate\Database Eloquent ORM outside of Laravel? If yes, how?

Answer

christianleroy picture christianleroy · Jan 7, 2016

Eloquent ORM needs to be initialized only once. Add the optional second parameter as the connection name.

$capsule = new Capsule;

$capsule->addConnection(
    array(
        'driver'    => 'mysql',
        'host'      => "localhost",
        'database'  => "employees_db",
        'username'  => "root",
        'password'  => "",
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),
    "default"
);

$capsule->addConnection(
    array(
            'driver'    => 'mysql',
            'host'      => "192.168.1.1",
            'database'  => "employees_db2",
            'username'  => "user",
            'password'  => "password",
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
    ),
    "employees"
        );

$capsule->setAsGlobal();
$capsule->bootEloquent();

When the above has been setup, you can then assign which database to connect to in your model file by writing the code below:

protected $connection = "employees";