Php 使用附加索引键自定义JSON响应
我在HTTP响应上使用Php 使用附加索引键自定义JSON响应,php,laravel,lumen,Php,Laravel,Lumen,我在HTTP响应上使用response()helper,如文档所示。简单的用法是: response()->json( $this->response, $this->status )->withHeaders([]); 这将输出: { "key" : "desired response" } 但是,我想在响应上添加一个键: $return['message'] = 'Request successful'; $return['data'] =
response()
helper,如文档所示。简单的用法是:
response()->json(
$this->response,
$this->status
)->withHeaders([]);
这将输出:
{
"key" : "desired response"
}
但是,我想在响应上添加一个键:
$return['message'] = 'Request successful';
$return['data'] = response()->json(
$this->response,
$this->status
)->withHeaders([]);
但结果是:
{
"message": "Request successful",
"data": {
"headers": {},
"original": {
"key" : "desired response"
},
"exception": null
}
}
响应上有额外的键:标题
,原始
&异常
。我如何才能消除这种情况,以实现这种理想的格式:
{
"message": "Request successful",
"data": {
"key" : "desired response"
}
}
你可以,拉威尔
并尝试在您的控制器处处理
$headers = 'Your header';
$originals = Your_Model::find(1);
return response()->success($headers, $originals);
return response()->error($validator->errors()->all(), 300);
您可以通过使用以下代码来实现这一点:
$return =[] ;
$return['message'] = 'Request successful'; // your message
$return['data'] = $this->response; // your data
return response()->json( // return json
$return, // your data here
$this->status // status here
);
不,我正在努力消除标题和原件。根据你的建议,这包括在内。我使用的是Lumen,似乎artisan的make:
中没有提供程序。为什么不使用return response()->json()…?@MortaddaJafar-正如您在我的帖子中看到的,我使用的是,只要我想添加自定义键,它就不会返回我想要的响应,而是添加键(异常、标题、原始)是的,您可以通过使用return response()->json(您的数据,,)来实现这一点。。
$headers = 'Your header';
$originals = Your_Model::find(1);
return response()->success($headers, $originals);
return response()->error($validator->errors()->all(), 300);
$return =[] ;
$return['message'] = 'Request successful'; // your message
$return['data'] = $this->response; // your data
return response()->json( // return json
$return, // your data here
$this->status // status here
);