Laravel: connect to databases dynamically

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.

Leave a Comment