I am trying to configure master/slave db connection in a handy way. The cleaner way I came across is using read/write hosts separately in database config file.
'mysql' => [
'read' => [
'host' => '192.168.1.1',
],
'write' => [
'host' => '196.168.1.2'
],
'driver' => 'mysql',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
],
In some cases, I need to read the data from master db (without replication lag). Is there a way to specify this explicitly? Something like we pass connection name to connection() method?
If you'd like to force eloquent to use the write connection in a one liner you can always do the following:
$user = User::onWriteConnection()->find(1);
Few minutes back I found that it is possible by specifying 'mysql::write' to the db connection method. So if we need to read data from master db using the configuration in my question, we can do something like, DB::connection('mysql::write')
. Hoping it would be useful for someone else.
I created read/write hosts separately and I follow modular approach in my application. If you want to force a particular model to fetch data from write head then in Laravel model you need to define connection for example:
class YourModelName extends Model {
protected $connection = 'mysql::write';
public $table = 'YourTableName';
}
In above example protected $connection = 'mysql::write'; force your application to execute mysqlselect statement from write head where ever you use YourModelName
I would start by creating two separate mySql connections, mysqlMaster and mysqlSlave. Then I would set mysqlSlave as default.
Then you can just use the function setConnection('mysqlMaster') for when you need to access the master connection.
$model = new Model();
$model->setConnection('mysqlMaster');
$result = $model->find(1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With