Laravel 9 Multiple Database Connections Tutorial

Hello friends, now, let's look at an example of laravel 9 multiple database connections. If you are looking for an example of multiple database connections in laravel 9 you are in the right place, I simply explained how to use multiple database connections in laravel 9. You can understand the concept of laravel 9 multiple database connection. So laravel 9 has to explain some things for multiple db connections. Which I will explain to you simply.

We will first look at how to use a laravel 9 multiple db connection using the .env file. For this we will add the configuration variable to the .env file and use it in the database configuration file. You don't have to worry, you can just follow me, because I will also learn how to work with migration, model and database query for multiple database connection.

Now that we need to understand when laravel 9 will need to make multiple database connections, I can say that you will probably need it when you are working with a large number of projects. As we know that sometimes we need to use multiple database connections like MySQL, MongoDB etc. So let's follow the steps below.

Step 1 : Create Multiple Database


First we need 2 or more databse like

  • database1
  • database2

Step 2 : Multiple Database Connections With Edit .env Eile 

In this case, you must set a configuration variable in the .env file. Let's make something like this 

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database1
DB_USERNAME=root
DB_PASSWORD=root
   
DB_CONNECTION_2=mysql
DB_HOST_2=127.0.0.1
DB_PORT_2=3306
DB_DATABASE_2=database2
DB_USERNAME_2=root
DB_PASSWORD_2=root

Step 3 : Multiple Database Connections With Edit Database Config File

Now that we've edit the .env file, we'll need to utilise it in the config file, so open database.php and add a new connections key like this. 

<?php

use Illuminate\Support\Str;

return [

    .........
    .........

    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections setup for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */

    'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            'url' => env('DATABASE_URL'),
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
            'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
        ],

        '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'),
            ]) : [],
        ],

        'mysql_2' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL_2'),
            'host' => env('DB_HOST_2', '127.0.0.1'),
            'port' => env('DB_PORT_2', '3306'),
            'database' => env('DB_DATABASE_2', 'forge'),
            'username' => env('DB_USERNAME_2', 'forge'),
            'password' => env('DB_PASSWORD_2', ''),
            'unix_socket' => env('DB_SOCKET_2', ''),
            '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'),
            ]) : [],
        ],

        .............
        .............

    ],


    .............
    .............

];

Step 4  : Multiple Database Connections With Create Model:

  • this is a default model: App\Models\Category.php 
<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Category extends Model
{
    use HasFactory;

    protected $table = 'category';
   
    protected $fillable = [
        'name', 'description'
    ];
}
  • this is a second database model : App\Models\Artical.php
<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Artical extends Model
{
    use HasFactory;
  
    protected $connection = 'mysql_2';
    protected $table = 'hrm_source';
  
    protected $fillable = [
        'title', 'description'
    ];
}

Step 5 : Create Route Using Multiple Database

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

//Get categories using databse 1
Route::get('categories', 'CategoryController@getCategory')->name('getCategory');

//Get articals using databse 2
Route::get('articals', 'ArticalController@getArticals')->name('getArticals');

Step 6 : Create Controller Using Multiple Database

We need 2 Controller name for CategoryController and ArticalController. 

app/Http/Controllers/CategoryController.php

<?php
  
use App\Models\Category;
    
class CategoryController extends Controller
{
    public function getCategory()
    {
        $categories = Category::get();
        dd($categories);
    }
}

app/Http/Controllers/ArticalController.php

<php
use App\Models\Artical;
  
class ArticalController extends Controller
{
    public function getArticals()
    {
        $artical = new Artical;
        $artical->setConnection('mysql_2');
        $item = $artical->find(1);
        dd($item);
    }
}

Notes : dd() function use to print the data

Now done the demo if any issue releted multiple matabase ping me.

I hope it can help you...