Laravel: connect to databases dynamically

前端 未结 4 1959
盖世英雄少女心
盖世英雄少女心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 04:37

    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.

提交回复
热议问题