Laravel 10 Multiple Database Connection Example

Laravel 10 Multiple Database Connection Example

Sometimes, you need to connect multiple databases with your Laravel web application. So, In this tutorial, you will learn how to create and use multiple database connections using laravel 7, 8, 9, and 10 apps with example.

How to Use Multiple Database in Laravel Example

Laravel provides multiple database connection access functionality it’s very easy and simple. By using the following steps, you can connect multiple databases in laravel 7, 8, 9, and 10 apps; is as follows:

  • Prerequisites
  • Method 1: Without .env Database Connection
  • Method 2: With .env Database Connection
  • Usage 1: Custom Connection In Migration
  • Usage 2: Custom Connection In Model
  • Usage 3: Custom Connection In Controller
  • Usage 4: Custom Connection with Query Builder

Prerequisites

First of all, You need to download the fresh Laravel setup where will implement our example.

Method 1: Without .env Database Connection

In Laravel, a database configuration file is located on “config / database.php”. Here you can set up more than one or multiple database connections in laravel 7, 8, 9, and 10 web applications. If your app uses data from two different MySql databases, you can easily define them.

<?php
return => [
    'connections' => [
        // Default database connection
        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],
        // Custom new database connection
        'mysql2' => [
            'driver' => 'mysql',
            'host' => 'localhost',
            'port' => '3306',
            'database' => 'lara_multiple',
            'username' => 'root',
            'password' => '',
            'unix_socket' => '',
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],
    ]
]

Method 2: With .env Database Connection

Now first of all set up the second database credential in your project .env file. Update your .env file using the below code.

DB_CONNECTION_SECOND=mysql
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=multi_lara
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=

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.

<?php
return => [
    'connections' => [
        // Custom database connection
        'mysql2' => [
            'driver'    => env('DB_CONNECTION_SECOND'),
            'host'      => env('DB_HOST_SECOND'),
            'port'      => env('DB_PORT_SECOND'),
            'database'  => env('DB_DATABASE_SECOND'),
            'username'  => env('DB_USERNAME_SECOND'),
            'password'  => env('DB_PASSWORD_SECOND'),
            ...
        ],
    ]
]

Usage 1: Custom Connection in Migration

You can use the following example for the custom connection in your migration.

<?php
...
public function up()
{
    Schema::connection('mysql2')->create('multipost', function (Blueprint $table) {
        $table->increments('id');
        $table->string('post_title');
        $table->string('post_content');
        $table->timestamps();
    });
}
...

Open your terminal and go to your project root directory, After that run the below command for executing our migrations for the specific database connection.

php artisan migrate --database=mysql2

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

This command fixed your issue;

php artisan config:cache

Usage 2: Custom Connection In Model

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

<?php
class SomeModel extends Eloquent {
    protected $connection = 'mysql2';
}

Usage 3: Custom Connection In Controller

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

<?php
class xyzController extends BaseController
{
    public function someMethod()
    {
        $someModel = new SomeModel;
        $someModel->setConnection('mysql2');
        $something = $someModel->find(1);
        return $something;
    }
}

Usage 4: Custom Connection with Query Builder

You can also define a connection on the query builder.

DB::connection('mysql2')->select(...)->(...);

Conclusion

In this article, you have successfully created multiple database connections with the .env file and without using the .env file.

Recommended Laravel Tutorials

Recommended:-Laravel Try Catch

Please feel free to add the comment or submit your feedback.

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

One reply to Laravel 10 Multiple Database Connection Example

  1. totally the mass and superb tutorial dude….

Leave a Reply

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