How to use Multiple Database Connections in LARAVEL 10

Spread the love

Hello Guys,

If you’re looking to explore the intricacies of multiple database connections in Laravel 10, you’ve come to the right place. In this guide, we’ll provide a straightforward example of leveraging multiple database connections in Laravel 10 by updating your .env file for seamless database management.

Setting up multiple database connections can be extremely beneficial, especially when working with various database systems such as MySQL, MongoDB, and more. Whether you’re managing multiple projects or simply want to streamline your database management, follow these step-by-step instructions to get started:

  1. Update your .env File: We’ll begin by adding a configuration variable to your .env file, which is the heart of Laravel’s configuration system.
  2. Configure Database Files: The added variable in your .env file will be used to configure your database connections. We’ll walk you through this process, ensuring a smooth setup.
  3. Migrations and Models: Gain hands-on experience with migrations, models, and database queries tailored to your specific database connections. This is where you’ll see the real power of managing multiple databases in Laravel 10.

With this guide, you’ll have the skills and knowledge to efficiently handle multiple database connections in Laravel 10, making your development projects more manageable and versatile.

Example of Multiple Database Connections:

Also Read: How to use One to Many Eloquent Relationship in LARAVEL 10

ENV Variable:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=yourdatabase
DB_USERNAME=root
DB_PASSWORD=password
   
DB_CONNECTION_SECOND=mysql
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=yourdatabase2
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=password

Database Configuration:

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

Using DB to Obtain Data from Multiple Databases:

Also Read: How to Create a Custom Error Page in Laravel 10?

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

Migration with multiple database connections:

To facilitate multiple database connections, consider creating distinct database migrations.

Also Read: How to Resize Images Before Upload in LARAVEL 10

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

Model With Multiple Database Connections:

Default Model:
<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Product extends Model
{
    use HasFactory;
   
    protected $fillable = [
        'name', 'detail'
    ];
}
With Second Database in Model:
<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Product extends Model
{
    use HasFactory;
  
    protected $connection = 'mysql_second';
  
    protected $fillable = [
        'name', 'detail'
    ];
}

Multiple Database Connections in Controller:

Default Controller:
<?php
  
use App\Models\Product;
    
class ProductController extends BaseController
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function getRecord()
    {
        $products = Product::get();
        return $products;
    }
}
With Second Database in the Controller:

Also Read: How to get .env variable in blade and controller in LARAVEL?

<?php
use App\Models\Product;
  
class ProductController extends BaseController
{
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function getRecord()
    {
        $product = new Product;
        $product->setConnection('mysql_second');
        $something = $product->find(1);
        return $something;
    }
}

Dive into our collection of Laravel blogs – your go-to source for expert insights.

Leave a Comment