PHP

How to Create Multiple Database Connections in Lumen3 min read

How to create multiple database connections in Lumen.

Last week I was working on a project in which I need multiple Database connections. I need one separate database connection for reporting (Only for a read operation) and another for the rest of the work (Read & write both).

How to Create Multiple Database Connections in Lumen




Let’s first put the configuration of your both databases in a .env file. In .env file just make sure you enter the host, port, database, username and password for both the Databases.

In config/database.php  add a configuration array for your new database. In connections array, you’ll find MySQL and below that, you can add similar array.

For illustration purpose check this example.

Now you have added connection configurations, you can access them by using either DB facade or app() helper.

NOTE – For using different databases in your code, You need to define which database connection you need by passing in the name of the connection.

How to Create Read & Write Connections in Lumen & Laravel

If you want to setup separate DB connections for a read and write database. I mean one database connection only for select statement and another one for insert, update and delete statements.

Laravel & Lumen provides this functionality out of the box. You just need to configure this setting that’s it. Your master and slave DB connections are ready to use.

Leave a Comment