Online Snippets Library

Use multiple DB connections In Laravel

Some times we need to use more than one database for our application.In laravel we connect more than one database.

Define Connections

Open up the "app/config/database.php ".File path may change depending on your environment.Here we define more than one database connection.

<?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'    => '',
        ),
         # Other database connection
          'pgsql' => array(
          'driver'   => 'pgsql',
          'host'     => 'localhost',
          'database' => 'forge',
          'username' => 'forge',
          'password' => '',
          'charset'  => 'utf8',
          'prefix'   => '',
          'schema'   => 'public',
        ),
    
    ),
);

Use different database connection in Schema Builder

To specify which connection to use in Schema Builder, simply run the connection() method like below.

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

Use different database connection in Query Builder

Here we use different connetion Query Builder for running query.

DB::connection('mysql2')->table('usersTable')->get();  

Use different database connection in Eloquent Models

Firsr we create "$connection" variable in our model.

<?php
class MyModel extends Eloquent {
    protected $connection = 'mysql2';
    protected $table = 'usersTable';
    // Primary Key
    protected $primaryKey = 'id';
    protected $fillable = array('id','firstName','lastName');   
    public $timestamps = false;
   }

We can also define the connection directly in controller via the sdetConnection method.

<?php
  class MyController extends BaseController {
    public function index()
    {
        $myModel = new MyModel;
        $myModel->setConnection('mysql2');
        $value = $myModel->find(1);
        return $value;
    }

}

remove-index.php-from-url-in-codeigniter