Using another connection in laravel project

Submitted by tuytoosh - 9 months 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 
DB_EXT_HOST=localhost
DB_EXT_DATABASE=db2
DB_EXT_USERNAME=username
DB_EXT_PASSWORD=password

//using in eloquent model 

<?php
class SomeModel extends Eloquent {
    protected $connection = 'mysql2';
}

//using in controller 


<?php
 
class SomeController extends BaseController {
 
    public function someMethod()
    {
        $someModel = new SomeModel;
 
        $someModel->setConnection('mysql2');
 
        $something = $someModel->find(1);
 
        return $something;
    }
 
}

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

Ads cover the costs of maintaining Laravel-tricks