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

左心房为你撑大大i 提交于 2020-01-29 20:48:26

问题


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.


回答1:


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);
});


来源:https://stackoverflow.com/questions/28645259/no-query-results-for-model-in-laravel-with-dingo-how-to-make-a-restful-respons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!