How to Connect multiple databases in laravel 5
Working with databases and running queries is simple in laravel. Also you can easily work with connect multiple databases in laravel. In laravel database configuration for your laravel application is located at config/database.php. This file contain database connections. You may define all of your database connections in this file. You may specify which connection should be used by default in return array like.
// Define default database for your application.
'default' => 'mysql',
This file included examples for all of the supported database systems. Now let’s start how to connect multiple databases in laravel 5. For this first go to your config/database.php, open it in your favorite editor and add your multiple databases under connections array.
代碼: 選擇全部
'connections' => [
// our primary default database.
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'laravelu'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
// our second database.
'mysql2' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
],
Accessing connection and running query with Query Builder :- Now let’s see how to run query with both databases. When we are using multiple connections, we can access each connection via the connection() method on the DB facade. The name passed to the connection method should correspond to one of the connections listed in your config/database.php configuration file. To run query you need to make first DB object then you can access data with this object easily like
代碼: 選擇全部
// Running query with default connection.
$userArray = DB::table('users')->get();
print_r($userArray);
// Makeing an object of second DB.
$users2 = DB::connection('mysql2');
// Getting data with second DB object.
$u = $users2->table('sc_items')->get();
print_r($u);
Note :- If you have an error with connections, or second db didn’t connect and showing error with “firstdb.table” not found.
Connect multiple databases in laravel
Go to “root/.env” file and remove initial database configuration (remove code looks like below) For more about Environment Configuration. Save .env file and run you queries.
代碼: 選擇全部
DB_HOST=localhost
DB_DATABASE=laravelu
DB_USERNAME=root
DB_PASSWORD=''