Skip to content
Advertisement

Laravel Resource Collection deletes my array keys

I have a resource-collection to get all my dialogues. Because the frontend is already coded (by another person), I want to return all of those as an object, with the dialogue_id of the database as keys and the dialogue object as values.

But when I want to convert the array I got from my resource collection (with (object) $array), it still returns an array without any of the keys I have set.

In my controller function I call:

JavaScript

My collection resource looks like the following:

JavaScript

What I get:

JavaScript

What I want to get:

JavaScript

Advertisement

Answer

When returning a resource collection from a route, Laravel resets the collection’s keys so that they are in simple numerical order. However, you may add a preserveKeys property to your resource class indicating if collection keys should be preserved. Put this above your code.

JavaScript

read docss here preserve keys

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement