Friday, August 21, 2015

Multiple DB Connections in Laravel 5. How to connect to a different Schema in Postgresql


What happens if you are using Laravel and PostgrSQL and you have to connect to multiple schemas. This post shows how to solve this problem easily in a few steps:



1) Create a new connection in the file app/config/database.php. For example the "test" connection linked to the "your_schema" schema.

...

'connections' => [

...

'test' => [
'driver'   => 'pgsql',
'host'     => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'homestead'),
'username' => env('DB_USERNAME', 'homestead'),
'password' => env('DB_PASSWORD', 'secret'),
'charset'  => 'utf8',
'prefix'   => '',
'schema'   => 'your_schema',
],

...
],

...

2) Create a new Model using artisan. For example: OtherDB model.


use Illuminate\Database\Eloquent\Model;

use Illuminate\Support\Facades\DB;

class OtherDB extends Model {

protected $connection = 'test'; // Connection name
protected $table = 'masterscale'; // table name

public $timestamps = false;

public static function loanSearch(){

$query = new OtherDB;

// Example 1: Using Eloquent
//dd($query::all());

// Example 2: Using a raw query
$masterscale = $query::where('risk_class','B1')->get();
foreach ($masterscale as $value) {
echo "
Risk class ". $value->risk_class . " has score " . $value->score;
}

//dd($masterscale);

return;
}

}


3) Create a controller with artisan or use an existing one. For example: otherDBController


use App\OtherDB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

class otherDBController extends Controller {

/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
$loans = OtherDB::loanSearch();
dd($loans);
}

}

4) Create the route to the controller is it does not exist

Route::resource('test', 'otherDBController');

5) Test it :)