Search code examples
laravellaravel-6laravel-6.2laravel-resource

Resource response is not wrapped with "data"


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?


Solution

  • 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