Resource response is not wrapped with “data” [duplicate]

瘦欲@ 提交于 2021-01-28 11:31:10

问题


I am very curious, why my resource response is not wrapped in data:

This is my resource:

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);

the output is

{
  "id": 12,
  "title": "Category",
  "description": "<p>Test</p>"
}

but according to https://laravel.com/docs/5.8/eloquent-resources#data-wrapping it should be:

{
  "data": {
    "id": 12,
    "title": "Category",
    "description": "<p>Test</p>"
  }
}

Why is the data-wrapper missing here?


回答1:


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.

See this: https://laravel.com/docs/5.8/eloquent-resources#writing-resources

Hope this helps you



来源:https://stackoverflow.com/questions/60027724/resource-response-is-not-wrapped-with-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!