资源响应不被“数据"包裹. [英] Resource response is not wrapped with "data"

查看:58
本文介绍了资源响应不被“数据"包裹.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇,为什么我的资源响应没有被包裹在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆