DWQA QuestionsCategory: LaravelSetup multiple database connection in laravel ?
kandy Staff asked 6 years ago

Example :
Step1: Add following code in database.php (path : config/database.php)

‘mysql_2’ => [
  ‘driver’ => ‘mysql’,
  ‘host’ => env(‘DB_HOST_2’, ‘localhost’),
  ‘port’ => env(‘DB_PORT_2’, ‘3306’),
  ‘database’ => env(‘DB_DATABASE_2’, ‘database_name’),
  ‘username’ => env(‘DB_USERNAME_2’, ‘root’),
  ‘password’ => env(‘DB_PASSWORD_2’, ‘root’),
  ‘charset’ => ‘utf8’,
  ‘collation’ => ‘utf8_unicode_ci’,
  ‘prefix’ => ”,
  ‘strict’ => true,
  ‘engine’ => null,
],

 
Step2: Add following Code in .ENV file

DB_CONNECTION_2=mysql_2
DB_HOST_2=localhost
DB_PORT_2=3306
DB_DATABASE_2=your_db_name
DB_USERNAME_2=user
DB_PASSWORD_2=password

Step3: Add following code in your model

/**
* The database name used by the model.
*
* @var string
*/
protected $connection = ‘mysql_2’;

Now rest of method you can use as usual.
-:)