Framework: withoutWrapping() applied to single resource affects other resources

Created on 9 Oct 2018  路  3Comments  路  Source: laravel/framework

  • Laravel Version: 5.5.43
  • PHP Version: 7.1.10
  • Database Driver & Version: MySQL 5.6.17

Description:

When applying withoutWrapping() to a single resource via AppServiceProvider, it affects other resources too.

Steps To Reproduce:

I have a CountryCollection that by default produces the following, which is correct:

{
    "data": [
        {
            "id": 1,
            "title": "Afghanistan",
            "code": "AF",
            "dialing": "35593"
        },
        {
            "id": 2,
            "title": "Albania",
            "code": "AL",
            "dialing": "355"
        },

I also have a DeviceResource that returns a single item only, as follows:

{
    "data": {
        "id": 6,
        "type": "Phone",
        "language": "en-GB",

I want the "data" wrapping removed for this one resource only.

In my AppServiceProvider, I add the following:

DeviceResource::withoutWrapping();

This has the desired effect on my DeviceResource output:

{
    "id": 6,
    "type": "Phone",
    "language": "en-GB",

But for some reason, affects my CountryResource by stripping the "data" wrapper that I would like to stay:

[
    {
        "id": 1,
        "title": "Afghanistan",
        "code": "AF",
        "dialing": "35593"
    },
    {
        "id": 2,
        "title": "Albania",
        "code": "AL",
        "dialing": "355"
    },

The only way I can get it to work as I need, is by removing the line in AppServiceProvider, and adding it in the code just before returning the resource:

DeviceResource::withoutWrapping();

return new DeviceResource($device);

Am I missing something here? Why does applying withoutWrapping() to DeviceResource in the AppServiceProvider also affect my other resources?

Most helpful comment

Does this answer your question? If you want to apply withoutWrapping() to a single resource, you have to put Resource::withoutWrapping(); in the respective controller.

All 3 comments

It affects all resources because JsonResource::$data is a static property.

DeviceResource::withoutWrapping(); has the same effect as JsonResource::withoutWrapping();.

Does this answer your question? If you want to apply withoutWrapping() to a single resource, you have to put Resource::withoutWrapping(); in the respective controller.

Does this answer your question? If you want to apply withoutWrapping() to a single resource, you have to put Resource::withoutWrapping(); in the respective controller.

It does, thank you.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fideloper picture fideloper  路  3Comments

Anahkiasen picture Anahkiasen  路  3Comments

JamborJan picture JamborJan  路  3Comments

lzp819739483 picture lzp819739483  路  3Comments

felixsanz picture felixsanz  路  3Comments