Laravel Multiple Database Connection – this is way to setup and work with multiple database connection in Laravel
Define connections in config file app/config/database.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php return array( 'default' => 'mysql', 'connections' => array( # Our primary database connection 'mysql' => array( 'driver' => 'mysql', 'host' => 'host1', 'database' => 'database1', 'username' => 'user1', 'password' => 'pass1' 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ), # Our secondary database connection 'mysql_2' => array( 'driver' => 'mysql', 'host' => 'host2', 'database' => 'database2', 'username' => 'user2', 'password' => 'pass2' 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ), ), ); |
Use the second DB in Eloquent Model
1 2 3 4 5 6 |
<?php class SomeModel extends Eloquent { protected $connection = 'mysql_2'; } |
Use the second DB Connection in Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php class SomeController extends BaseController { public function someMethod() { $someModel = new SomeModel; $someModel->setConnection('mysql_2'); $something = $someModel->find(1); return $something; } } |
Query Builder
1 |
$users = DB::connection('mysql_2')->select(...); |