Using another connection in laravel project

Submitted by tuytoosh - 6 years ago

If you want to use(or work with) another database in a section of your project use following steps... step 1. Create another connection in config/database.php step 2. Insert new connection info in .env file... step 3. Tell to laravel to use this new connection

//create connection in config/database.php
'mysql2' => [
            'driver'    => 'mysql',
            'host'      => env('DB_EXT_HOST', 'localhost'),
            'database'  => env('DB_EXT_DATABASE', 'db2'),
            'username'  => env('DB_EXT_USERNAME', 'username'),
            'password'  => env('DB_EXT_PASSWORD', 'password'),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
//edit .env file 

//using in eloquent model 

class SomeModel extends Eloquent {
    protected $connection = 'mysql2';

//using in controller 

class SomeController extends BaseController {
    public function someMethod()
        $someModel = new SomeModel;
        $something = $someModel->find(1);
        return $something;

//using in Query builder
$users = DB::connection('mysql2')->select(...);