0

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,
        ];
    }
SPQRInc
  • 162
  • 4
  • 23
  • 64

2 Answers2

1

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.

Radu Diță
  • 13,476
  • 2
  • 30
  • 34
0

It's in the definition. Laravel's resource classes allow you to expressively and easily transform your models and model collections into JSON. Check the Resource docs

If you are expecting an array in return then I suggest skip resource and pass the data directly from the controller using ->toArray(). But then again you are using axios in your vuejs then I strongly recommend to stick with json format as an expected response.

Digvijay
  • 7,836
  • 3
  • 32
  • 53