Change database connections on the fly.
Yazan Stash • April 7, 2019
We're all familiar with how to change the settings for our database connection, hope into the
.env file and edit away.
but what if we wanted to change the connection settings mid-request?
The way Laravel reads those settings is by accessing the
Illuminate\Config\Repository. So, we can tap into the repository and update our settings on the fly, for example:
config()->set('database.connections.mysql.host', '123.456.78.321'); config()->set('database.connections.mysql.port', '3307'); config()->set('database.connections.mysql.database', 'PRODUCTION');
Cool! that's it? uh hmm, not really...
This will only work if it was done before any database related command is executed. otherwise, the connection would be established already and Laravel will use the already opened connection instead of creating a new one with the updated settings.
But, we can tell Laravel to use the new settings by calling
reconnect() on the
DB facade like so,
This can be used in a multi-tenant app where tenants' database settings are stored on the main connection and used to dynamically connect to their database.
Wanna say something ? shoot me at firstname.lastname@example.org