php - Laravel - 返回 json 和 http 状态码

标签 php json laravel http-status-codes

如果我返回一个对象:

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(引用自:https://stackoverflow.com/a/14717895/2025923):

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

关于php - Laravel - 返回 json 和 http 状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31131159/

相关文章:

php - 用php创建白色图像

java - 使用 Firebase 检索双向关系中的用户 - Android

php - 从数组中提取 id 和 name

php - 一对多关系 - Laravel 和 Mysql

php - Laravel 5.4 - 在集合中使用自定义属性模型

php - 如何运行 php 脚本来发送推送通知

javascript - 使用php从angularjs中的数据库中获取数据

php - 摆脱这个代理

javascript - 动态添加带有jquery错误的元素

json - 如何在 Node-RED 函数中解析 JSON