Support the ongoing development of Laravel.io →
posted 10 years ago
Database

I'm fairly new to laravel 4 and have a question regarding the automated connection selection for read/write mysql connections. This is working quite well and makes life quite easy. However, there are some cases where I need to be able to force a SELECT statement to use the Write connection instead of the Read connection.

Haven't had a chance to dig into the code too much in this area yet, and my search attempts on this question haven't been met with any results. Is this possible within the base code?

Last updated 2 years ago.
0

I ran into this issue too. The only way I could figure to do it was to create another database connection entry in my database.php config file.

'mysql' => array(
    'driver'    => 'mysql',
    'read' => array(
        'host' => 'read-host',
        'database'  => 'read-database',
        'username'  => 'read-username',
        'password'  => 'read-password',		       
    ),
    'write' => array(
        'host' => 'write-host',
        'database'  => 'write-database',
        'username'  => 'write-username',
        'password'  => 'write-password',		       
    ),
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),
'mysql-write' => array(
    'driver' => 'mysql',
    'host' => 'write-host',
    'database'  => 'write-database',
    'username'  => 'write-username',
    'password'  => 'write-password',		       
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

Then when you need to force a select using the write connection, you can do this:

DB::connection('mysql-write')->select(...);

Or if you are using Eloquent:

User::on('mysql-write')->find(1);
Last updated 2 years ago.
0

See: http://laravel.com/api/5.1/Illuminate/Database/Eloquent/Model.html#method_onWriteConnection

It allows you to query the model on the write connection.

Example use:

User::onWriteConnection()->find(1);
0
        $r = DB::connection($this->connection)
                ->selectFromWriteConnection("CALL maker_create_service_order(?, ?, ?, ?, ?, ?);",[
                    $creationId, $accountId, $storeId, $storeProductId, $quantity, $total
                ]);

This works fine for me.

0

Is this working in laravel 5.3 tried to do so by its seems that its not working

0

Sign in to participate in this thread!

Eventy

Your banner here too?

ricktbaker ricktbaker Joined 25 May 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.