Search code examples
phpapirestlaraveldingo-api

No query results for model in Laravel with Dingo - how to make a RESTful response on failure?


I'm creating an API with Laravel based on the Dingo API.

In my routes, I have:

Route::api('v1', function () {
    Route::resource('object', 'My\Namespace\MyController');
});

And in MyController:

class MyController extends \Illuminate\Routing\Controller {

    use Dingo\Api\Routing\ControllerTrait;

    public function index() {
        return MyObject::all();
    }

    public function show($id) {
        return MyObject::findOrFail($id);
    }

}

This means that api.domain.com/object calls MyController@index, which works. Since there are no items in the database, this then outputs an empty json array [].

api.domain.com/object/123 calls MyController@show(123). This is according to https://github.com/dingo/api/wiki/Responses. However, since there are no results in the database, I get:

No query results for model [My\Namespace\MyObject].

I would expect this to give a nice RESTful error instead. How do I do that?

The code of MyObject is nothing special, it's an empty class which extends Illuminate\Database\Eloquent\Model.

I'm using Laravel 4.2; 5 is not supported by Dingo yet.


Solution

  • You'll have to handle it yourself and add a custom error as described here. findOrFail() will throw a ModelNotFoundException so let's catch that:

    API::error(function (Illuminate\Database\Eloquent\ModelNotFoundException $e){
        return Response::make(['error' => 'Resource not found'], 404);
    });