Laravel - Return json along with http status code

对着背影说爱祢 提交于 2019-11-28 17:43:18
Tushar

You can use http_response_code() to set HTTP response code.

If you pass no parameters then http_response_code will get the current status code. If you pass a parameter it will set the response code.

http_response_code(201); // Set response status code to 201

For Laravel(Reference from: https://stackoverflow.com/a/14717895/2025923):

return Response::json([
    'hello' => $value
], 201); // Status code here
Jeremy C.

This is how I do it in Laravel 5

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

Or using a helper function:

return response()->json(['hello' => $value], 201); 
TKoutsou

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;
iSensical

There are multiple ways

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

return response()->json(['hello' => $value], STATUS_CODE);

where STATUS_CODE is your HTTP status code you want to send. Both are identical.

if you are using Eloquent model, then simple return will also be auto converted in JSON by default like,

return User::all();
return response(['title' => trans('web.errors.duplicate_title')], 422); //Unprocessable Entity

Hope my answer was helpful.

I prefer the response helper myself:

    return response()->json(['message' => 'Yup. This request succeeded.'], 200);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!