Laravel: connect to databases dynamically

前端 未结 4 1958
盖世英雄少女心
盖世英雄少女心 2020-11-29 03:52

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 connec

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 04:34

    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');
    

提交回复
热议问题