How to Use Multiple Database Connections in Laravel Application

How to Use Multiple Database Connections in Laravel Application

When you need multiple database connection in Laravel PHP then you can use DB facade via connection method.

In other way you can simply setup another database connection in config/database.php and then you create protected variable for connection like this protected $connection = 'mysql_2';

Here is a simple step to use multiple database connection in Laravel.

Setup multiple database

Create another database connection by this way :


  1.         'mysql' => array(
  2.             'driver' => 'mysql',
  3.             'host' => 'localhost',
  4.             'database' => 'xyz',
  5.             'username' => 'root',
  6.             'password' => '',
  7.             'charset' => 'utf8',
  8.             'collation' => 'utf8_unicode_ci',
  9.             'prefix' => '',
  10.         ),
  11.         'mysql1' => array(
  12.             'driver' => 'mysql',
  13.             'host' => 'localhost',
  14.             'database' => 'abc',
  15.             'username' => 'root',
  16.             'password' => '',
  17.             'charset' => 'utf8',
  18.             'collation' => 'utf8_unicode_ci',
  19.             'prefix' => '',
  20.         ),

Now as per need create database connection variable in your model.

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. class Product extends Model
  5. {
  6. protected $connection = 'mysql1';
  7. }

Phone: (+91) 8800417876
Noida, 201301