Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Read/Write Connection - Specify Explicitly

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?

like image 222
Tibin Paul Avatar asked May 31 '16 16:05

Tibin Paul


4 Answers

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);

like image 170
gsaqui Avatar answered Nov 15 '22 01:11

gsaqui


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.

like image 23
Tibin Paul Avatar answered Nov 15 '22 00:11

Tibin Paul


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

like image 40
Aditya Singh Avatar answered Nov 15 '22 02:11

Aditya Singh


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);
like image 1
Amarnasan Avatar answered Nov 15 '22 00:11

Amarnasan