Multiple database connections in laravel 5 Application

By Hardik Savani | May 8, 2016 | | 4582 Viewer | Category : Laravel


Share this post:

you can set multiple database connections in same laravel application. Laravel provide configration file for setup multiple database connections. you can see config/database.php file and see mysql multiple database connections. you can add setting another mysql database detail like this way:

config/database.php

return [


'fetch' => PDO::FETCH_CLASS,


'default' => env('DB_CONNECTION', 'mysql'),


'connections' => [

'sqlite' => [

'driver' => 'sqlite',

'database' => database_path('database.sqlite'),

'prefix' => '',

],


'mysql' => [

'driver' => 'mysql',

'host' => env('DB_HOST', 'localhost'),

'database' => env('DB_DATABASE', 'forge'),

'username' => env('DB_USERNAME', 'forge'),

'password' => env('DB_PASSWORD', ''),

'charset' => 'utf8',

'collation' => 'utf8_unicode_ci',

'prefix' => '',

'strict' => false,

'engine' => null,

],


'mysql2' => [

'driver' => 'mysql',

'host' => 'localhost',

'database' => 'college',

'username' => 'root',

'password' => 'root',

'charset' => 'utf8',

'collation' => 'utf8_unicode_ci',

'prefix' => '',

'strict' => false,

'engine' => null,

],


'pgsql' => [

'driver' => 'pgsql',

'host' => env('DB_HOST', 'localhost'),

'database' => env('DB_DATABASE', 'forge'),

'username' => env('DB_USERNAME', 'forge'),

'password' => env('DB_PASSWORD', ''),

'charset' => 'utf8',

'prefix' => '',

'schema' => 'public',

],


'sqlsrv' => [

'driver' => 'sqlsrv',

'host' => env('DB_HOST', 'localhost'),

'database' => env('DB_DATABASE', 'forge'),

'username' => env('DB_USERNAME', 'forge'),

'password' => env('DB_PASSWORD', ''),

'charset' => 'utf8',

'prefix' => '',

],


],


'migrations' => 'migrations',


'redis' => [


'cluster' => false,


'default' => [

'host' => env('REDIS_HOST', 'localhost'),

'password' => env('REDIS_PASSWORD', null),

'port' => env('REDIS_PORT', 6379),

'database' => 0,

],


],


];

You can use multiple mysql database like this way:

Example:

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

print_r($users);

$users = DB::connection('mysql2')->table("users")->get();

print_r($users);



We are Recommending you: