简体   繁体   中英

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.

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

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:

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. 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 .

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.

So the above is equal to:

return $classrooms;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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