使用 Dingo 在 Laravel 中没有模型的查询结果 - 如何在失败时做出 RESTful 响应? [英] No query results for model in Laravel with Dingo - how to make a RESTful response on failure?
问题描述
我正在使用基于 Dingo API 的 Laravel 创建 API.
I'm creating an API with Laravel based on the Dingo API.
在我的路线中,我有:
Route::api('v1', function () {
Route::resource('object', 'My\Namespace\MyController');
});
在 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);
}
}
这意味着 api.domain.com/object
调用了 MyController@index
,这是有效的.由于数据库中没有项目,因此会输出一个空的 json 数组 []
.
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
调用 MyController@show(123)
.这是根据 https://github.com/dingo/api/wiki/Responses.但是,由于数据库中没有结果,我得到:
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].
我希望这会给出一个很好的 RESTful 错误.我该怎么做?
MyObject 的代码没有什么特别的,它是一个扩展 Illuminate\Database\Eloquent\Model
的空类.
The code of MyObject is nothing special, it's an empty class which extends Illuminate\Database\Eloquent\Model
.
我使用的是 Laravel 4.2;Dingo 尚不支持 5.
I'm using Laravel 4.2; 5 is not supported by Dingo yet.
推荐答案
您必须自己处理并添加自定义错误,如此处.findOrFail()
会抛出一个 ModelNotFoundException
所以让我们抓住这个:
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);
});
这篇关于使用 Dingo 在 Laravel 中没有模型的查询结果 - 如何在失败时做出 RESTful 响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!