2

I am trying to connect Eloquent to multiple databases sqlserver for the default and mongodb for the secondary connection. I am using jenssegers/laravel-mongodb pulled in using composer. Here is my database file

use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;

$capsule->addConnection([
        'driver'   => 'sqlsrv',
        'host'     => '******',
        'database' => '*****',
        'username' => '*****',
        'password' => '*****',
        'prefix'   => '',
    ], 'default');

$capsule->addConnection([
        'driver'   => 'mongodb',
        'host'     => 'localhost',
        'port'     => 27017,
        'username' => '',
        'password' => '',
        'database' => 'production'
], 'mongo');

$capsule->setAsGlobal();
$capsule->bootEloquent();

The problem is when i try and connect to the mongo database it throws the following error:

InvalidArgumentException thrown with message "Unsupported driver [mongodb]"

It looks to me that the Illuminate connection factory does not support mongodb out of the box, could someone please point me in the right direction to get this working?

Gaurav Dave
  • 6,838
  • 9
  • 25
  • 39
gmann1982
  • 97
  • 1
  • 9

2 Answers2

4

You're right it does not have native support. But it's easy to add:

composer require jenssegers/mongodb:*

and then:

use Illuminate\Database\Capsule\Manager as Capsule;
use Jenssegers\Mongodb\Connection as Connection;

$capsule = new Capsule();

$capsule->getDatabaseManager()->extend('mongodb', function($config){
    return new Connection($config);
});
evilive
  • 1,781
  • 14
  • 20
3

I have found that the answer by evilive, and an additional line of code is required to properly tie the capsule in to Jenssenger models:

Jenssegers\Mongodb\Model::setConnectionResolver($capsule->getDatabaseManager());

The call to

$capsule->bootEloquent();

binds the various connection resolvers/database managers to the Eloquent models, but it doesn't seem to bind them to the Jessenger ones.

jakalofnaar
  • 111
  • 2