How to Use Multiple Databases in Laravel
In this article, you can use multiple databases in Laravel. Here we can define more than one database connection of any type.
.env file
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=devnote1
DB_USERNAME=root
DB_PASSWORD=123456
DB_CONNECTION_SECOND=mysql
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=devnote2
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=456789
config/database.php file
'mysql' => [
'driver' => env('DB_CONNECTION'),
'host' => env('DB_HOST'),
'port' => env('DB_PORT'),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
],
'mysql2' => [
'driver' => env('DB_CONNECTION_SECOND'),
'host' => env('DB_HOST_SECOND'),
'port' => env('DB_PORT_SECOND'),
'database' => env('DB_DATABASE_SECOND'),
'username' => env('DB_USERNAME_SECOND'),
'password' => env('DB_PASSWORD_SECOND'),
],
Simple run the connection() method
Schema
Schema::connection('mysql2')->create('some_table', function($table)
{
$table->increments('id'):
});
Query Builder
$users = DB::connection('mysql2')->select(......);
Eloquent
class HomeModel extends Eloquent {
protected $connection = 'mysql2';
}
Controller
class HomeController extends BaseController {
class HomeController extends BaseController {
public function create()
{
$homeModel = new HomeModel;
$homeModel->setConnection('mysql2');
$returnVar = $homeModel->find(1);
$returnVar = HomeModel::on('mysql2')->find(1);
return $returnVar;
}
}