phpmysqllaravel-5illuminate-container

Illuminate Database connectivity with mysql router


I'm using Laravel's illuminate database library outside laravel with jessengers mongodb.

My requirement is multiple database connectivity through illuminate database.

Currently, I've added two connection one mysql and one mongodb.

To split the database load, I need to connect to mysql router instead of mysql db server directly. Also, in that I want one only for Read operation and one for Read/Write operation.

Kindly help me out on this.

Thanks in advance.

Current connections

$db = new Capsule;

$db->addConnection([
    'driver'    => 'mysql',
    'host'      => '127.0.0.1',
    'database'  => 'test',
    'username'  => 'test',
    'password'  => 'test@123#',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
], "default");

$db->addConnection([
    'driver'   => 'mongodb',
    'host'     => '127.0.0.1',
    'port'     => 27017,
    'database' => 'test',
    'username' => null,
    'password' => null,
    'options' => []
], "mongodb");

$db->getDatabaseManager()->extend('mongodb', function ($config) {
    return new Connection($config);
});

$db->setEventDispatcher(new Dispatcher(new Container));
$db->setAsGlobal();
$db->bootEloquent();

I need to replace one mysql connection with two mysql connection for Read and Read/Write operation through mysql router.


Solution

  • You can define read/write options separately with either mysql host or mysql router host and port

    $db->addConnection([
        'driver'    => 'mysql',
        'read'      => [
            'host'      => '<mysql_router_host_ip>',
            'port'      => '<mysql_router_host_port>'
        ],
        'write'     => [
            'host'      => '<mysql_router_host_ip>',
            'port'      => '<mysql_router_host_port>'
        ],
        'database'  => '<mysql_database>',
        'username'  => '<mysql_database_user>',
        'password'  => '<mysql_database_password>',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ], "mysql");