Roi
Roi

Reputation: 565

Laravel 5.5 How to change DB_HOST on request

Ok, my system connects to remote databases on which I consistently change depending on what data I want to access.

The setup is multiple identical structure databases resides on different IP addresses, so I always update the .env DB_HOST line every time I want to access different database.

Now I'm planning to create a view on my system that will accepts an IP address and set it as the current database to use.

Upvotes: 1

Views: 1203

Answers (1)

John Ellmore
John Ellmore

Reputation: 2229

Referencing this answer on Laracasts:

Set two database connections in your config (one for your unchanging main connection, the other one for your custom dynamic connection):

'main' => array(
    'driver'   => 'mysql',
    'host'     => 'hostname',
    'database' => 'database',
    'username' => 'username',
    'password' => 'password',
    'prefix'   => '',
),

'dynamic' => array(
    'driver'   => 'mysql',
    'host'     => '',
    'database' => '',
    'username' => '',
    'password' => '',
    'prefix'   => '',
),

Then change your database connection parameters for the second connection as needed:

Config::set('database.connections.dynamic.host', $newHost);
Config::set('database.connections.dynamic.username', $newUsername);
Config::set('database.connections.dynamic.password', $newPassword);
Config::set('database.connections.dynamic.database', $newDatabase);
Config::set('database.default', 'dynamic');

And reconnect the database:

DB::reconnect('mysql');

Upvotes: 2

Related Questions