资源响应不被“数据"包裹. [英] Resource response is not wrapped with "data"
问题描述
我很好奇,为什么我的资源响应没有被包裹在data
中:
I am very curious, why my resource response is not wrapped in data
:
这是我的资源
App\Http\Resources\CategoryResource Object
(
[resource] => stdClass Object
(
[id] => 12
[title] => Category
[description] => <p>Test</p>
[with] => Array
(
)
[additional] => Array
(
)
)
以这种方式返回此资源后:
Once this resource is returned like this:
$response = $this->client->getApiResponse('/api/category/'.$id); //response comes from third-party-API
$data = new CategoryResource(json_decode ($response->getContents())->data);
return response()->json($data);
输出为
{
"id": 12,
"title": "Category",
"description": "<p>Test</p>"
}
,但根据 https://laravel.com/docs/5.8/eloquent-resources#data-wrapping 应该是:
{
"data": {
"id": 12,
"title": "Category",
"description": "<p>Test</p>"
}
}
为什么这里缺少 data
-wrapper?
Why is the data
-wrapper missing here?
推荐答案
数据包装器仅适用于onresource集合.如我所见,您没有资源收集.资源集合用于返回结果集合.您将返回单个类别.因此,您应该使用ResourceCollection或手动包装它.
Data wrapper works only onresource collection. As i see you don't have resource collection. Resouce collection is used to return collection of results. You are returning single category. So you should use ResourceCollection or wrap it manually.
查看此内容: https://laravel.com/docs/5.8/eloquent-resources#writing-resources
希望这对您有帮助
这篇关于资源响应不被“数据"包裹.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!