How to use multiple databases in Laravel

How to use multiple databases in Laravel

Using Multiple Database Connections in Laravel

 Step 1: Set Up Database Connections in .env

In your root .env file, define both primary and secondary database credentials like this:

# Primary DB DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=database1 DB_USERNAME=root DB_PASSWORD=secret # Secondary DB DB_CONNECTION_SECOND=mysql DB_HOST_SECOND=127.0.0.1 DB_PORT_SECOND=3306 DB_DATABASE_SECOND=database2 DB_USERNAME_SECOND=root DB_PASSWORD_SECOND=secret

Step 2: Configure Connections in config/database.php

Add the second connection in the connections array:

'mysql' => [ 'driver' => env('DB_CONNECTION', 'mysql'), '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', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], 'mysql2' => [ 'driver' => env('DB_CONNECTION_SECOND', 'mysql'), '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', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ],

Step 3: Get Data from the Second Database

You can now query data from both connections:

Example: Primary DB

$data = DB::table('users')->get();

Example: Secondary DB

$dataFromSecond = DB::connection('mysql2')->table('your_table')->get();

Bonus: Use Models with Custom Connection

If you're using Eloquent models, you can specify the connection like this:

class Product extends Model { protected $connection = 'mysql2'; // use the second DB protected $table = 'products'; // optional }

Now you can call:

Product::all(); // this will pull from mysql2 connection

Summary

TaskCommand / Code
Define DBs.env variables
Configureconfig/database.php
Query Secondary DBDB::connection('mysql2')->table('table')->get()
Use in Modelprotected $connection = 'mysql2';
Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close