Laravel - Multiple Database Connections Example

About Us:

We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you.
free coder

Today what you are going to learn:

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);

Recent Posts

Related Posts