Dynamic database connection in Laravel 5.5 | Multiple database connection in Laravel 5.5 | MySQL & Redis database connection in Laravel | Change database or schema dynamically in a connection

So many time If we are working on a big application we need to keep out data in multiple databases. This is very easy to manage multiple database connections in Laravel. You also can create your database connection at run time.

Inside your database configuration file you can define multiple database connections. Like in Laravel 'config/database.php' we can define our multiple database connections.

We also can set our database or schema dynamically within a database connection.

I will show you 3 MySQL and 1 Redis database connection as multiple database connection and I also will connect them dynamically.

Here is the routing file which I have used.

routes/web.php

I will get users list from MySQL database and keywords list from Redis.

For using Redis you have to install predis module in your Laravel project. You can install in Laravel through the below command:

Here is the connections in 'config/database.php' like:

Here I have defined 3 MySQL database connections named as mysql1, mysql2 and mysql3. I also have created one Redis database connection.



\App\Http\Controllers\UserController.php

Here in getUsers function I have set the connection dynamically by setConnection() function.

I'm also defined that how can you set the schema dynamically within a single MySQL database connection like:

If you noticed I have passed connection name and schema as parameters for MySQL and connection name for Redis in routing. You can pass connection name and schema name according to your need.

I have set the connection name and set the schema name in getUsers() function, You can use this functionality as per your need like you can create septate middle ware for this.

For model I have used users model like:

\App\User.php

Here is the Controller for keywords, I'll display the keywords from Redis.

App\Http\Controllers\KeyWordsController.php

I also have set the connection name here dynamically.



\App\KeyWords.php

 

Share This:

Leave a Reply

Your email address will not be published. Required fields are marked *