Laravel 10 Multiple Database Connections Example - TechvBlogs

Laravel 10 Multiple Database Connections Example

In this article, You will learn How to use multiple database connections in Laravel 10.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

1 year ago

TechvBlogs - Google News

In Laravel 10, you can define and use multiple database connections in your application. This feature is useful when you need to connect to multiple databases or data sources within the same application.

To define multiple database connections, you can add new connections to the config/database.php file. Each connection should have a unique name and configuration options, such as the database driver, host, username, and password.

Once you have defined the database connections, you can use them throughout your application by specifying the connection name in your database queries. You can switch between database connections dynamically, allowing you to interact with multiple databases or data sources seamlessly within the same application.

Overall, using multiple database connections in Laravel 10 provides a powerful and flexible way to manage multiple data sources within your application.

Set ENV Variable:

Here, you need to set configuration variable on .env file. let's create as bellow:

.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

Database Configuration:

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

config/database.php

<?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'),
            ]) : [],
        ],
        'mysql_second' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL_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' => env('DB_SOCKET_SECOND', ''),
            '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'),
            ]) : [],
        ],
.....        

Getting Data from Multiple Database using DB:

I will give write two routes with getting products from different database connections. you can see simple example with DB.

Let's add two routes in your file:

routes/web.php

<?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!
|
*/
  
/*------------------------------------------
--------------------------------------------
Getting Records of Mysql Database Connections
--------------------------------------------
--------------------------------------------*/
Route::get('/get-mysql-blogs', function () {
    $products = DB::table("blogs")->get();
      
    dd($products);
});
  
/*------------------------------------------
--------------------------------------------
Getting Records of Mysql Second Database Connections
--------------------------------------------
--------------------------------------------*/
Route::get('/get-mysql-second-blogs', function () {
    $products = DB::connection('mysql_second')->table("blogs")->get();
      
    dd($products);
});

Multiple Database Connections with Migration:

You can create separate migrations for multiple database connections:

Default:

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

Second Database:

<?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();
    });
}
.....

Multiple Database Connections with Model:

Default:

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

Second Database:

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

Multiple Database Connections in Controller:

Default:

<?php

namespace App\Http\Controllers;

use App\Models\Blog;
    
class BlogController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function getRecord()
    {
        $blogs = Blog::get();
        return $blogs;
    }
}

Second Database:

<?php

namespace App\Http\Controllers;

use App\Models\Blog;
    
class BlogController extends Controller
{
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function getRecord()
    {
        $blog = new Blog;
        $blog->setConnection('mysql_second');
        $something = $blog->find(1);
        return $something;
    }
}

Thank you for reading this article.

Comments (0)

Comment


Note: All Input Fields are required.