Mark Topper
Mark Topper

Reputation: 664

Change connection on Builder->get()

I was wondering, are there any hacks in order to change the connection in the get-method of Illuminate\Database\Query\Builder.

I have already extended the Query\Builder with a custom get-method.

The problem is that I do not see any methods to change the connection from the Query\Builder. Is it to late to change the connection? Or can I extend any thing in order to be able to change the connection inside the get-method.

Why I'm trying to do this, is because I'm creating a package for laravel to control 2 connections from models.

So lets say that they want a users to use Connection #1 while getting data from MyModel, but if a user is Admin, then they should get the data from Connection #2. But they should still both save data into Connection 1.

It's kinda hard to explain, but are there a method I can use to change the connection inside the get-method.

And I'm not looking for a way to change the actually connection in the newQuery-method, since that gives me lots of other troubles.

Upvotes: 0

Views: 424

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

Query\Builder won't help here, for there's no way to change the connection on the already instantiated builder.

But, connection is a dependency that you can swap in your get method. Simply replace $this->connection with another one (ConnectionInterface). You can use ConnectionFactory for this.

However there's probably a better way for you - Read/Write connections. Laravel makes it easy to use different setup for read and write statements, so I suggest you just set the config to something like this:

'mysql' => array(
    'driver'    => 'mysql',
    'host'      => HOST,
    'database'  => DB,
    'username'  => USER,
    'password'  => PASS,
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

'mysql_for_admin' => array(
    'driver'    => 'mysql',
    'write'     => [
        'host'      => HOST,
        'database'  => DB,
        'username'  => USER,
        'password'  => PASS,
    ],
    'read'     => [
        'host'      => ANOTHER_HOST,
        'database'  => ANOTHER_DB,
        'username'  => ANOTHER_USER,
        'password'  => ANOTHER_PASS,
    ]
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

Just adjust these entries to your needs and use the connection depending on the user's role.

Read more about read/write connections: http://laravel.com/docs/database#read-write-connections

Upvotes: 2

Related Questions