Laravel 10 Multiple Database Connections Example
Apr 13, 2023 . Admin

Hi Guys,
Do you want your Laravel 10 application to connect to many databases? You might occasionally run into a situation where you have to work with many databases. The use of numerous database connections in a Laravel 10 application is covered in this article. Several database connections are supported by Laravel's core code.
We will talk about "How to utilise Multiple Database Connections in Laravel 10" in this article. Several databases may need to be connected to the Laravel application under certain circumstances.
As we all know, there are instances when we need to use numerous connections to databases like MySQL, MongoDB, etc. I can tell that if you work on many different projects, you might need. So let's proceed in order.
Download LaravelLet us begin the tutorial by installing a new Laravel application. if you have already created the project, then skip the following step.
composer create-project laravel/laravel example-appSet ENV Variable:
Here, you need to set the configuration variable on the .env file. let's create as bellow:
.envDB_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=rootDatabase Configuration:
Now, as we created a variable in the env file, we need to use that variable on the config file so let's open the database.php file and add a new connections key as like below:
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 for getting products from different database connections. you can see a simple example with DB.
let's add two routes to 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! | */ Route::get('/get-mysql-products', function () { $products = DB::table("products")->get(); dd($products); }); Route::get('/get-mysql-second-products', function () { $products = DB::connection('mysql_second')->table("products")->get(); dd($products); });Multiple Database Connections with Migration:
you can create separate migrations for multiple database connections:
Default:<?php /** * Write code on Method * * @return response() */ public function up() { Schema::create('blog', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->string('body')->nullable(); $table->timestamps(); }); }Second Database:
<?php /** * Write code on Method * * @return response() */ public function up() { Schema::connection('mysql_second')->create('blog', 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 Product extends Model { use HasFactory; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'detail' ]; }Second Database:
<?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'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'detail' ]; }Multiple Database Connections in Controller: Default:
<?php use App\Models\Product; class ProductController extends BaseController { /** * Write code on Method * * @return response() */ public function getRecord() { $products = Product::get(); return $products; } }Second Database:
<?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; } }
I hope it can help you...