If you want to access multiple databases at a time, you need to create different database connections to manage your business requirement. Laravel has the capability to handle multiple different types of data sources in the same application.
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci'
],
'mysql2' => [
'driver' => 'mysql',
'host' => env('DB2_HOST', '127.0.0.1'),
'port' => env('DB2_PORT', '3306'),
'database' => env('DB2_DATABASE', 'forge'),
'username' => env('DB2_USERNAME', 'forge'),
'password' => env('DB2_PASSWORD', ''),
'unix_socket' => env('DB2_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci'
],
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=root
DB2_CONNECTION=mysql
DB2_HOST=127.0.0.1
DB2_PORT=3306
DB2_DATABASE=test2
DB2_USERNAME=root2
DB2_PASSWORD=root2
There are multiple ways to use them.
Use it as a Row Query:
$users = DB::table('users')->get(); // first Database query
$users2 = DB::connection('mysql2')->table(‘users')->get(); // second Database query
Use it in Eloquent Models:
We need to specify the connection in the model.
protected $connection = mysql2; //We need to specify this connection in the class
After the connection is defined, if you need to retrieve all user details using mysql2, you just need to write User::all().
Using Migration:
If you want to run a migration on the specific database then we need to use
- -database
Using this concept, we can develop a highly scalable and flexible application that can manage several data resources very efficiently. A developer can easily manage and use the multi-database by using multiple database configurations.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Laravel Expertise.