Achmad Fatoni
Achmad Fatoni

Reputation: 21

laravel 5.6 keep array custom key in resource response

from laravel documentation: The withoutWrapping method only affects the outer-most response and will not remove data keys that you manually add to your own resource collections.

i use Resource::withoutWrapping();

`"status": "success"
    "entry": {
        "access_control": [
            1 => {
                "allowed": [
                    0 => "015"
                    1 => "002"
                    2 => "011"
                 ]
}`

in laravel 5.6 i can't define custom array key, key under access_control key become 0.'

How to make api resource support custom key?

Upvotes: 2

Views: 1877

Answers (2)

Jafo
Jafo

Reputation: 1331

Another way around this would be to use stdClass();

$array = new \stdClass();
$array->access_control = ['somedata'];

Then it should pass it as an object.

Upvotes: 3

MikeC
MikeC

Reputation: 45

Array key are removed when the JsonResource applies it's filter method. There does not seem a way to retain those keys.

For my particular use case, I was able to refactor the array value to include it's "id" - in your case:

"access_control": [
    {
        "id": 1,
        "allowed": [
            "015"
            "002"
            "011"
        ]
    }
]

Upvotes: 2

Related Questions