Search code examples
laravelvue.jsaxioslaravel-7laravel-resource

Array is returned as an object using resource


something strange is going on.

I got an array like this:

=> [
     "optionalinformation" => [
       "domain" => [
         "type" => "string",
       ],
     ],
   ]

This array is used by a resource and if I use tinker to check this resource like this:

$result = App\Http\Resources\ProductResource::make(Product::find(2));

is_array($result->optionalinformation);

In this case the result is true: This is an array.

But if axios fetches the result, I am getting this:

"optionalinformation": {
      "domain": {
        "type": "string"
      },

It's no longer an array but an object. Any ideas why this is happening?

This is my api-resource:

 /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'                      => $this->id,
            'title'                   => $this->title,
            'optionalinformation'     => $this->optionalinformation,
        ];
    }

Solution

  • There is a bit of confusion here, mostly caused by PHP lingo.

    In PHP lingo an associative array is still an array. But an associative array is actually a dictionary.

    Other programming languages don't see an associative array (dictionary) as an array and as such have a different vocabulary.

    Your data structure is actually a dictionary, and not a numerical indexed array.

    From a JSON perspective if your data structure has non-numerical keys then it gets translated to an object.

    Your confusion stems from the fact that is_array will return true if the variable is a zero based indexed array, when in fact it returns true for associate arrays also.