Laravel - Return json 以及 http 状态代码

Laravel - Return json along with http status code

如果我return一个对象:

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

状态代码将为 200。如何将其更改为 201,并通过消息将其与 json 对象一起发送?

不知道有没有办法只在Laravel中设置状态码。

您可以使用 http_response_code() 设置 HTTP 响应代码。

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

对于Laravel(参考自:):

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

这就是我在 Laravel 5

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

或者使用辅助函数:

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

有多种方式

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

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

其中 STATUS_CODE 是您要发送的 HTTP 状态代码。两者是相同的。

如果您使用的是 Eloquent 模型,那么简单的 return 也会 自动转换为 JSON 默认情况下,

return User::all();

我认为将您的回复置于单一控制之下是更好的做法,因此我找到了最官方的解决方案。

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

namespace 声明后添加:

use Illuminate\Http\Response;
return response(['title' => trans('web.errors.duplicate_title')], 422); //Unprocessable Entity

希望我的回答对您有所帮助。

我自己更喜欢回复助手:

    return response()->json(['message' => 'Yup. This request succeeded.'], 200);

最好使用 辅助函数 而不是 Facades。从 Laravel 5.7 开始,此解决方案将运行良好

//import dependency
use Illuminate\Http\Response;

//snippet
return \response()->json([
   'status' => '403',//sample entry
   'message' => 'ACCOUNT ACTION HAS BEEN DISABLED',//sample message
], Response::HTTP_FORBIDDEN);//Illuminate\Http\Response sets appropriate headers

laravel 7.* 您不必指定 JSON RESPONSE 因为它会自动将其转换为 JSON

return response(['Message'=>'Wrong Credintals'], 400);