jloosli
jloosli

Reputation: 2581

Return array in Laravel API Resource without reordering keys

In my API, I use resources for all the endpoints. For the most part, I'm returning arrays of data and they work just fine. However, for a couple of endpoints, I have some data that looks something like the following:

[
  "123" => ["total"=>123, "average"=>12.7],
  "456" => ["other"=>"data"],
]

where the keys are the ids for other objects already provided by the API. However, when I send that data to the resource, the response essentially turns the data into a straight array, so the JSON representation looks as follows:

[
  ["total": 123, "average": 12.7],
  ["other": "data"]
]

I'm thinking this is more of an issue issue with json_encode underneath the hood, but is there anything I can do in the toArray() method to keep the keys when they're numeric strings? The only things that have worked for me so far are to prepend a non-numeric string key (e.g. dummy to the object), or to add a letter to each key (e.g. a123, a456, etc.).

Upvotes: 0

Views: 1904

Answers (2)

glenz0r
glenz0r

Reputation: 53

A bit late but for anyone having the same issue, you can do this right now:

class MyCustomResource extends JsonResource
{
    /**
     * Keep resource keys as they are.
     * If set to `false` (default), the JsonResource's filter will flatten the array/collection without numerical keys
     *
     * @var boolean
     */
    protected $preserveKeys = true;
}

Upvotes: 3

Jaime Rojas
Jaime Rojas

Reputation: 559

You could try sending your response from the controller back with Laravel's integrated JSON converter:

$toJson = [
      "123" => ["total"=>123, "average"=>12.7],
      "456" => ["other"=>"data"],
 ];
 return response()->json($toJson);

This will succesfully return a JSON looking like this:

{
  '123': {
    total: 123,
    average: 12.7,
  },
  '456': {
    other: "data",
  },
}

Upvotes: 0

Related Questions