Laravel-返回json和http状态码 [英] Laravel - Return json along with http status code
本文介绍了Laravel-返回json和http状态码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我返回一个对象:
return Response::json([
'hello' => $value
]);
状态码将为200.如何将其更改为201,并显示一条消息并与json对象一起发送?
the status code will be 200. How can I change it to 201, with a message and send it with the json object?.
我不知道是否有一种方法可以在Laravel中设置状态代码.
I don't know if there is a way to just set the status code in Laravel.
推荐答案
You can use http_response_code()
to set HTTP response code.
如果未传递任何参数,则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
对于Laravel(引用自: https://stackoverflow.com/a/14717895/2025923 ):>
For Laravel(Reference from: https://stackoverflow.com/a/14717895/2025923):
return Response::json([
'hello' => $value
], 201); // Status code here
这篇关于Laravel-返回json和http状态码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文