When developing a web application, we may need to use multiple databases due to project requirements or large-scale projects; in these cases, Laravel supports multiple database connections. This blog will teach you how to use multiple databases with Laravel.
Add Database Connection Detail in
.env
DB_HOST_SECOND="DB HOST HERE"
DB_PORT_SECOND="DB PORT HERE"
DB_DATABASE_SECOND="DATABASE NAME HERE"
DB_USERNAME_SECOND="DB USERNAME HERE"
DB_PASSWORD_SECOND="DB PASSWORD HERE"
Configure database detail in config / database.php
add detail in the connections array.
<?php
return [
'connections'=>[
'mysql'=>[
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'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', ''),
],
'mysql_second'=>[
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST_SECOND', '127.0.0.1'),
'port' => env('DB_PORT_SECOND', '3306'),
'database' => env('DB_DATABASE_SECOND', 'forge'),
'username' => env('DB_USERNAME_SECOND', 'forge'),
'password' => env('DB_PASSWORD_SECOND', ''),
]
]
];
?>
We will now look at how to use this connection with Schema, Query, and Eloquent Model.
Schema Builder
Schema::connection('mysql_second')->create('table_name', function($table){
// entire code here
});
Query Builder
$posts = \DB::connection('mysql_second')->select('id','title')->get();
Eloquent Model
<?php
namespace App\Models;
class Post extends Eloquent {
protected $connection = 'mysql_second';
}
?>
The connection can also be used in custom join queries. using the following simple example:
\DB::table('posts')->join('mysql_second.types as secondDbType','posts.code','=','secondDbType.code')->first();
All the best nerd!