Laravel: dynamically connect to databases

I am building an application in Laravel 5 (.1) where you need to connect to various databases. The only problem is that he did not know which databases he should connect to, so using database.php in config is not possible. The controller is responsible for connecting to dynamically given communication details.

How can I create a new database connection, including using the DB class? (Or is it possible)

Thanks in advance!

+12
source share
3 answers

The easiest solution is to configure the database at run time. Laravel can expect these settings to be loaded from a file config/database.php, but that does not mean that you cannot install or change them later.

The configuration loaded from config/database.phpis saved as databasein the Laravel configuration. This means that the array connectionsinside config/database.phpis stored in a file database.connections.

Thus, you can easily override / modify these connections as follows:

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

From now on, all Eloquent models using this connection mysqlwill use this new database connection configuration.

I would recommend doing this at a service provider, if possible.

+16
source

.

.

config(), .

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

, . , , , .

DB::purge('mynewconnection');

, . , . , ...

DB::setDefaultConnection('mynewconnection');
+9

- ,

0

Source: https://habr.com/ru/post/1681431/


All Articles