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:

return new DialogueResourceCollection($dialogues);

My collection resource looks like the following:

class DialogueResourceCollection extends ResourceCollection
{
    /**
     * Transform the resource into an array.
     *
     * @param  IlluminateHttpRequest $request
     * @return array
     */
    public function toArray($request)
    {
       $array = [];
        for ($i = 0; $i < sizeof($this); $i++) {
            $j = $this[$i]->dialogue_id;
            $array[$j] = $this[$i];
        }

        return $array;
    }
}

What I get:

[
    {
        "dialogue_id": 1,
        "text": "example text"
    }, 
...

What I want to get:

{
 "34" :   {
        "dialogue_id": 34,
        "text": "example text"
    }, 
...
}

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.

public $preserveKeys = true;

read docss here preserve keys

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