Laravel Multiple Database Connections Example

Hello Artisan

In this tutorial we will discuss about laravel multiple database connections. Do you know how to connect laravel multiple database connections? If you don't know then you are right place. In this tutorial i will show you step by step that multiple db connection in laravel 7/6.

You know that sometime we need to setup multiple database connection like mysql, mongodb etc. i can say when you work with large amount of project then you will need maybe. So let's follow bellow step to learn multiple database connection in laravel 7/6.

I will add configuration variable on .env file and use it to database configuration file. You can just follow this laravel 7/6 multiple database connections tutorial, i will also teach how to work with migration, model and database query for multiple database connection.

You have to set configuration variable on .env file. do it.

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mydatabase
DB_USERNAME=root
DB_PASSWORD=root

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

 

Now, as i created variable in .env file, we need to use that variable on config/database.php file so let's open database.php file and add new connections key as like bellow:

config/database.php

use Illuminate\Support\Str;
  
return [
   
    'default' => env('DB_CONNECTION', 'mysql'),
   
    'connections' => [
        .....
   
        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            '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' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],
        'mysql2' => [
            'driver' => env('DB_CONNECTION_SECOND'),
            'host' => env('DB_HOST_SECOND', '127.0.0.1'),
            'port' => env('DB_PORT_SECOND', '3306'),
            'database' => env('DB_DATABASE_SECOND', 'forge'),
            'username' => env('DB_USERNAME_SECOND', 'forge'),
            'password' => env('DB_PASSWORD_SECOND', ''),
            'unix_socket' => '',
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
        ],

 

Here, i will give you simple example of how we can use as multiple connection to create migration. So to create migration just add which connection are you going to use.

public function up()
{
    Schema::connection('mysql2')->create('blog', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('body')->nullable();
        $table->timestamps();
    });
}

 

Now we need to setup every model as like below before working with database.

namespace App;
  
use Illuminate\Database\Eloquent\Model;
   
class Blog extends Model
{
    protected $connection = 'mysql2';
}

 

Now we have to user controller method as like below

class BlogController extends BaseController
{
    public function getRecord()
    {
        $blogModel = new Blog;
        $blogModel->setConnection('mysql2');
        $find = $blogModel->find(1);
        return $find;
    }
}

 

If you need to use query builder, then just follow and use this method.

$blogs = DB::table("blog")->get();
print_r($blogs);
   
$blogs = DB::connection('mysql2')->table("blog")->get();
print_r($blogs);

 

Read also : Laravel Queue Tutorial With Redis And Horizon

 

Hope this multi database connection laravel 7/6 tutorial will help you.