Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: connect to databases dynamically

I'm creating an application in Laravel 5(.1) where it is needed to connect to different databases. The only problem is that it's not known which databases it has to connect to, so making use of the database.php in config is not possible. A controller is in charge of making a connection with dynamically given connection details.

How can I make a new connection to a database, including making use of the DB class? (Or is this possible)

Thanks in advance!

like image 695
Roboroads Avatar asked Mar 18 '16 13:03

Roboroads


2 Answers

The simplest solution is to set your database config at runtime. Laravel might expect these settings to be loaded from the config/database.php file, but that doesn't mean you can't set or change them later on.

The config loaded from config/database.php is stored as database in Laravel config. Meaning, the connections array inside config/database.php is stored at database.connections.

So you can easily override/change these connections like this:

Config::set("database.connections.mysql", [     "host" => "...",     "database" => "...",     "username" => "...",     "password" => "..." ]); 

From there on out, any Eloquent models that use this mysql connection will be using this new database connection config.

I'd recommend doing this in a Service Provider if possible.

like image 183
jszobody Avatar answered Sep 22 '22 23:09

jszobody


I've stumbled upon the same problem.

You can actually change database settings in runtime and use them.

Use the config() function to set extra or overwrite existing connection settings.

config(['database.connections.mynewconnection' => {settings here}]); 

Keep in mind that these settings are cached. So when you need to use the new settings, purge the DB cache for the connection you're gonna use.

DB::purge('mynewconnection'); 

You can also manipulate the default connection that is used. This can come in handy if you wish to use migrations over different connections and keep track of them with a migration table within the used connection. Or other cool stuff ofcourse...

DB::setDefaultConnection('mynewconnection'); 
like image 31
feskr Avatar answered Sep 22 '22 23:09

feskr