2

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?

SPQRInc
  • 162
  • 4
  • 23
  • 64

1 Answers1

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

Malkhazi Dartsmelidze
  • 4,783
  • 4
  • 16
  • 40
  • 1
    Actually when you return a `ModelResource` from a route or controller directly instead of wrapping it with a `response()` it does wrap it properly. – reppair Mar 28 '21 at 19:23
  • 1
    Exactly what @reppair said, `response()` removes wrap, returning resource works fine. Anyone know why? – rock3t Aug 12 '21 at 13:35
  • 1
    When you return `SomeResource` directly from controller, as it is responsable Laravel calls `toResponse` to get response. If you look at `toResponse` method, it gets array using `toArray` and then wraps it with `data` key **No Matter What**. When you return `response(SomeResoure)` it calls `toArray` and returns `json_encode(result_of_toArray)`, without wrapping. If you want to return unwrapped resource directly from `Controller` You can use this syntax: `SomeResource::collection($data)->toArray(request())`. It will return unwrapped Array. – Malkhazi Dartsmelidze Aug 12 '21 at 14:03