Laravel 7/6 Multiple Database Connections In one application

In this tutorial you will learn about the Laravel 7/6 Multiple Database Connections In one application and its application with practical example.

In this Laravel 7/6 Multiple Database Connections In one application tutorial I will show you how to connect or use multiple database in single laravel project. In this tutorial you will learn to connect or use multiple database in single laravel project.

In this tutorial, we would love to share with you how to connect single or multiple databases using a laravel application. Sometimes, we need to connect multiple databases to the Laravel application.

Laravel 7/6 Multiple Database Connections In one application

  • Without .env Database Connection
  • With .env Database Connection
  • Custom Connection In Migration
  • Custom Connection In Model
  • Custom Connection In Controller
  • Custom Connection with Query Builder
  • Conclusion

Without .env Database Connection

In Laravel, there is a database configuration file is located on “config/database.php”.  From this file you can set up more than one database connection. If your app uses data from two different MySql databases, you can easily define them.

With .env Database Connection

Next, you can set the database credential in your project .env file and then update your “config/database.php” with the following code given below.

Custom Connection in Migration

Open your terminal and switch to your project directory, Now, run the following command to run our migrations for the specific database connection.

If you found any error when we execute the migrate command. So that time you can clear your config cache, we will provide the command below:

This command fixed your issue;

Custom Connection In Model

You can set the “$connection” variable in your model. So use the below code for that:

Custom Connection In Controller

You can also define the connection in your controller using the “setConnection” method.

Custom Connection with Query Builder

You can also define a connection on the query builder.

In this tutorial we have learn about the Laravel 7/6 Multiple Database Connections In one application and its application with practical example. I hope you will like this tutorial.