Normally Laravel provides a single database connection by default. But we can connect multiple databases very easily. From this tutorial, you will learn how to create multiple database connection in laravel 9 application. You will learn laravel 9 multiple database connections in this tutorial. 

You have already known that Laravel provides a .env configuration file in the project root path. We can connect multiple database configurations in Laravel using this file. So let's see the example code of multiple db connection in laravel 9.

Update ENV:

Here, you need to set the configuration variable on the .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

 

Read also: How To Connect SQlite Database In Laravel?

 

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

 

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

 

Multiple Database Connections for Migration:

You can create separate migrations for multiple database connections:

Default:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
};

 

With another database connect for migration:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::connection('mysql_second')->create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
};

 

Multiple Database Connections for Model:

The model with default connection:

Default:

<?php

namespace App\Models;

use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'email',
        'password',
    ];
}

 

With another database connect to the model:

<?php

namespace App\Models;

use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens, HasFactory, Notifiable;
    
    protected $connection = 'mysql_second';

    protected $fillable = [
        'name',
        'email',
        'password',
    ];
}

 

Fetching Multiple Database Connections Data From Controller:

The default way to fetch data from the controller like:

Default

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

 

The way to fetch data from the controller with another database connection like:

<?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;
    }
}

 

Read also: How To Connect PostgreSQL Database In Laravel?

 

Conclusion

I have tried to discuss the clear concept of laravel sqlite setup. Now we know how to connect sqlite database in laravel. Hope this how to connect to sqlite database in laravel tutorial will help you.