phplaravellaravel-resource

Laravel resource converting my associative array into a standard array


PHP 7.4.16 & Laravel 8.61

I have the following code in my Resource:

   $arr = ['id' => $this->id, 'associations' => (object)[]];
   foreach ($tas as $ta) {
       $ta_id = $ta->id;
       $arr['associations']->$ta_id = ['suppliers' => [], 'offices' => []];
   }
   return $arr;

Where $ta->id is a integer.

When I print the Resource::collection of an item, I can see the associations with the right id as key being printed.

0:
-> associations:
--> 2:
---> ['suppliers' => [], 'offices' => []]

However, when I print a single resource (new Resource(item)), the associations array becomes a standard array.

associations:
-> 0:
--> ['suppliers' => [], 'offices' => []]

Why is this happening? Is there any workaround?


Solution

  • All you need is to add ->toArray(null) to your resource like this example that i tried before

    BookingResource::collection($timeSlots)->toArray(null);