Tom Fisher Tom Fisher - 6 months ago 101
PHP Question

How would I connect to two databases in laravel 5.2, one SQL and one SQL Server?

I'm looking online and the only examples are of the same type of database.

Any help would be appreciated!

Answer

First you need to define configuration for your connections in config/database.php, just make sure you fill in all required parameters:

'connections' => [
    'mysql' => [
        'driver' => 'mysql',
        'host' => '',
        'port' => '',
        'database' => '',
        'username' => '',
        'password' => '',
        'charset' => '',
        'collation' => '',
        'prefix' => '',
        'strict' => false,
        'engine' => null,
    ],
    'sqlsrv' => [
        'driver' => 'sqlsrv',
        'host' => '', 
        'database' => '',
        'username' => '',
        'password' => '',
        'prefix' => '',
    ],
],

Then you need to set one of those connections as the default connection Eloquent uses in `config/database.php':

'default' => 'mysql', //use mysql by default

MySQL connection will be used by default by all your models and queries.

You can change the connection given model uses by setting it's $connection attribute:

class User extends Model {
  protected $connection = 'sqlsrv';
}

You can also change the connection used when you execute queries using DB facade by calling the connection() method:

DB::connection('sqlsrv')->table('some_table')->get();
Comments