简体   繁体   English

在 Laravel 中返​​回 ResourceCollection 时如何返回 HTTP 状态码

[英]How to return HTTP status code when returning a ResourceCollection in Laravel

I'm building an API and I'm trying to return a ResourceCollection for a Classroom in Laravel.我正在构建一个 API,我正在尝试为 Laravel 中的教室返回一个 ResourceCollection。

Previously I used an array of classrooms and returned a response with the array and the status code, like this:以前我使用了一个教室数组,并返回了一个包含数组和状态代码的响应,如下所示:

$classrooms=Classroom::all();
return response()->json($classrooms,200);

Now this is my code:现在这是我的代码:

$classrooms = new ClassroomCollection(Classroom::paginate(10));
   return $classrooms;

to get this response:得到这个回应:

"data": [classrooms array],
"links": {
        "first": "http://127.0.0.1:8000/api/classrooms ?page=1",
        "last": "http://127.0.0.1:8000/api/classrooms ?page=1",
        "prev": null,
        "next": null
         },
"meta": {
        "current_page": 1,
        "from": null,
        "last_page": 12,
        "path": "http://127.0.0.1:8000/api/classrooms ",
        "per_page": 10,
        "to": null,
        "total": 0
         }

and I can't find a way to send a status code along with the ClassroomCollection, because if I do而且我找不到将状态代码与 ClassroomCollection 一起发送的方法,因为如果我这样做了

return response()->json($classrooms,200);

I'm only returned the "data" object, without the links and meta of the paginator.我只返回了“数据”对象,没有分页器的链接和元数据。

Any help?有什么帮助吗?

you can override the withResponse function in your collection like this:您可以像这样覆盖集合中的 withResponse 函数:

public function withResponse($request, $response)
{
    if($response->getData()) {
        $response->setStatusCode(200);
    } else{
        $response->setStatusCode(404);
    }
    parent::withResponse($request, $response);
}

If you really want to you can do the following:如果你真的想要,你可以执行以下操作:

return response()->json($classrooms->jsonSerialize(), 200);

->jsonSerialize() does not actually serialize as a JSON string but returns an array that can be serialized to JSON string. ->jsonSerialize()实际上并不序列化为 JSON 字符串,而是返回一个可以序列化为 JSON 字符串的数组。 Laravel serializes to a JSON response if you return an array or JsonSerializable able object from a controller/route and that is what the paginator implements .如果您从控制器/路由返回一个数组或JsonSerializable对象,那么 Laravel 将序列化为 JSON 响应,而这正是分页器实现的

However, if 200 is the status code you want, that is implied and the default status code and there is no need to supply it.但是,如果200是您想要的状态代码,则这是隐含的默认状态代码,无需提供。

So the above is equal to:所以上面的等价于:

return $classrooms;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM