Laravel-mongodb: Type error: Argument 1 passed to Jenssegers\Mongodb\Query\Builder::__construct() must be an instance of Jenssegers\Mongodb\Connection, instance of Illuminate\Database\MySqlConnection given

Created on 5 Jul 2017  路  4Comments  路  Source: jenssegers/laravel-mongodb

Methods like firstOrCreate, firstOrNew don't work on laravel 5.4.
When calling them i get this error:

Type error: Argument 1 passed to Jenssegers\Mongodb\Query\Builder::__construct() must be an instance of Jenssegers\Mongodb\Connection, instance of Illuminate\Database\MySqlConnection given,

I've found a workaround, which should be fixed in the package itself. The problem was when calling

Illuminate\Database\Eloquent::resolveConnection($connection = null)

and passing null, because DatabaseManager just took the default connection in this case.
My fix was extending this method in my model and hardcoding the connection name inside it.

    /**
     * Resolve a connection instance.
     *
     * @param  string|null  $connection
     * @return \Illuminate\Database\Connection
     */
    public static function resolveConnection($connection = null)
    {
        return static::$resolver->connection('mongodb');
    }

Just setting

    protected $connection = 'mongodb';

doesn't work. I've tried setting it through __construct(), calling $this->setConnection() and some other stuff, but it still wouldn't work. It probably gets overwritten somewhere.

I just might be missing something extremely obvious.

question

Most helpful comment

I had the same Issue today and remembered the .env file which overrides the config files.
Maybe this will fix it for you too!

All 4 comments

Hello here is an example that works with us.

<?php

namespace App;

//use Jenssegers\Mongodb\Eloquent\Model;
use Illuminate\Database\Eloquent\Model;
use Jenssegers\Mongodb\Eloquent\HybridRelations;

class Profil extends Model
{

    use HybridRelations;

    protected $connection = 'mysql';

    public function adresses(){
        return $this->hasMany("App\Adresse",'profils_id');
    }
}

I had the same Issue today and remembered the .env file which overrides the config files.
Maybe this will fix it for you too!

I had the same Issue today and remembered the .env file which overrides the config files.
Maybe this will fix it for you too!

I tried doing the same. But it did'nt help me!

fix DB_CONNECTION=mongodb , it's worked for me

Was this page helpful?
0 / 5 - 0 ratings

Related issues

yupangestu picture yupangestu  路  3Comments

geofflancaster picture geofflancaster  路  3Comments

HassanIbrahim picture HassanIbrahim  路  3Comments

sebastiaanluca picture sebastiaanluca  路  3Comments

ricardofontanelli picture ricardofontanelli  路  3Comments