Search code examples
eloquentlaravel-5laravel-query-builderdingo-apilumen-5.2

Dingo API, use Database Query Builder


Does anyone know how can I use the Eloquent Query Builder with Dingo API ?

Using Eloquent out of the box, it is working great :

use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;
$capsule->addConnection([ ... ]);

$capsule->setAsGlobal(); // Make this Capsule instance available globally via static methods
$capsule->bootEloquent(); // Setup the Eloquent ORM

And then in my model, I can use the Query Builder :

use Illuminate\Database\Capsule\Manager as Capsule;

Capsule::table('users')->where(...)->select(Capsule::raw('AVG(rating) AS avg_rating'))->first()->avg_rating;

I know that I can use Eloquent to get the same result, but it will only work with easy query :

User::where(..)->selectRaw(...)->first()->avg_rating;

Now with Dingo API, when I wanna use the Query Builder I've got this error message :

Fatal error: Call to a member function connection() on null

I guess that is related to the setAsGlobal method that I have never called in my app/bootstrap.php file. I only have this :

...
$app = new Laravel\Lumen\Application(
    realpath(__DIR__.'/../')
);

// $app->withFacades();

$app->withEloquent();
...

Solution

  • I got it. It was only about Facades.

    Uncomment the line in app/bootstrap.php to use Facades :

    $app->withFacades();
    

    Now, I can use the Facade 'DB' and so the Query Builder...