资源响应未用 "data" 包裹

Resource response is not wrapped with "data"

我很好奇,为什么我的资源响应没有包裹在data:

这是我的资源:

App\Http\Resources\CategoryResource Object
(
    [resource] => stdClass Object
        (
            [id] => 12
            [title] => Category
            [description] => <p>Test</p>

    [with] => Array
        (
        )

    [additional] => Array
        (
        )

)

一旦资源返回如下:

$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?

数据包装器仅适用于资源集合。如我所见,您没有资源收集。资源收集用于 return 结果收集。您正在 returning 单一类别。所以你应该使用 ResourceCollection 或手动包装它。

看到这个:https://laravel.com/docs/5.8/eloquent-resources#writing-resources

希望对您有所帮助