How to Use Multiple Database in Laravel 11?

How to Use Multiple Database in Laravel 11

Laravel is a strong PHP framework capable of managing multiple database connections in a single application. It comes in useful while working with microservices, separation of read/write operations, or different types of databases. Here in this blog, we are going to find out how to configure and work with multiple databases in Laravel 11.

Hire laravel Developer

Steps to Use Multiple Database in Laravel 11:

Step 1: Create .env file in your Laravel project directory

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blogs
DB_USERNAME=root
DB_PASSWORD=user123
   
DB_CONNECTION_TWO=mysql
DB_HOST_TWO=127.0.0.1
DB_PORT_TWO=3306
DB_DATABASE_TWO=blogs2
DB_USERNAME_TWO=root
DB_PASSWORD_TWO=user123

Step 2: Now we need to use that variable in the config file. Open the config/database.php file, and insert the following code

<?php

use Illuminate\Support\Str;

return [

    'default' => env('DB_CONNECTION', 'sqlite'),

    'connections' => [...],

        'mysql' => [
            'driver' => 'mysql',
            'url' => env('DB_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'laravel'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => env('DB_CHARSET', 'utf8mb4'),
            'collation' => env('DB_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_second' => [
            'driver' => 'mysql',
            'url' => env('DB_URL_TWO'),
            'host' => env('DB_HOST_TWO', '127.0.0.1'),
            'port' => env('DB_PORT_TWO', '3306'),
            'database' => env('DB_DATABASE_TWO', 'laravel'),
            'username' => env('DB_USERNAME_TWO', 'root'),
            'password' => env('DB_PASSWORD_TWO', ''),
            'unix_socket' => env('DB_SOCKET_TWO', ''),
            'charset' => env('DB_CHARSET', 'utf8mb4'),
            'collation' => env('DB_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 3: Create a separate migration for multiple database connections 

First – 

<?php
.....
public function up(): void
{
    Schema::create('blogs', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('body')->nullable();
        $table->timestamps();
    });
}
.....

Second – 

<?php
.....
public function up(): void
{
    Schema::connection('mysql_second')->create('blogs', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('body')->nullable();
        $table->timestamps();
    });
}
.....

Step 4: Create Modal for both

First – 

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Model;
  
class Blog extends Model
{
    protected $fillable = [
        'title', 'body'
    ];
}

Second – 

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Model;
  
protected $connection = 'mysql_second';

class Blog extends Model
{
    protected $fillable = [
        'title', 'body'
    ];
}

Step 5: Controllers for Multiple Database Connections

First – 

<?php
  
use App\Models\Blog;
    
class BlogController extends Controller
{

    public function getData()
    {
        $blogs = Blog::get();
        return $blogs;
    }

}

Second –

<?php

use App\Models\Blog;
  
class BlogSecondController extends Controller
{
    
    public function getRecord()
    {
        $blog = new Blog;

        $blog->setConnection('mysql_second');

        $data = $blog->find(1);

        return $data;
    }

}

Step 6: In the Route file

Insert the following code in your web.php file

<?php

use App\Http\Controllers\FrontendController;
use Illuminate\Support\Facades\Route;


Route::get('/get-mysql-blogs', [BlogController::class, 'getData'])->name('mysql-blog');
Route::get('/get-mysql-second-blogs', [BlogSecondController::class, 'getRecord'])->name('mysql-second-blog');

Conclusion

It is easy to use multiple databases in Laravel 11 with its native database management system. This method is perfect for managing large-scale applications that need various data sources.

Laravel Development Services

If you face any difficulty, let me know through the comment section.

Previous Article

Magento 2 Extensions Digest February 2025 (New Release & Updates)

Next Article

How to Create and Register Middleware in Laravel 11?

Write a Comment

Leave a Comment

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

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨