Laravel - Return json along with http status code

后端 未结 8 1908
北恋
北恋 2020-12-08 03:57

If I return an object:

return Response::json([
    \'hello\' => $value
]);

the status code will be 200. How can I change it to 201, with

8条回答
  •  不知归路
    2020-12-08 04:14

    I think it is better practice to keep your response under single control and for this reason I found out the most official solution.

    response()->json([...])
        ->setStatusCode(Response::HTTP_OK, Response::$statusTexts[Response::HTTP_OK]);
    

    add this after namespace declaration:

    use Illuminate\Http\Response;
    

提交回复
热议问题