change database connection in laravel model
Different models can have different database connections. So your models use the normal default connection - but your 'McibModel' model can use another connection:
class McibModel extends Model {
protected $connection= 'second_db_connection';
protected $table = 'agencies';
}
Then in your DB connection file - you would have something like this:
return array(
'connections' => array(
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database1',
'username' => 'user1',
'password' => 'pass1'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
'second_db_connection' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database2',
'username' => 'user2',
'password' => 'pass2'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
),
In one way setting a protected property will always connect a particular model to a database.
class MyModel extends Model {
protected $connection = "second_db_connection";
}
In a query I like this approach...
(new MyModel())->on('second_db_connnection')->get();
I think for a lot of use cases it can be convenient to declare the connection at runtime like this:
$McibModel = new McibModel();
$McibModel->setConnection('second_db_connection');