0

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?

1
  • Didn't you ask this not long ago? Commented Oct 3, 2021 at 15:21

1 Answer 1

2

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

BookingResource::collection($timeSlots)->toArray(null);
Sign up to request clarification or add additional context in comments.

2 Comments

This does actually work, but why? My problem was that it was working for the collection but not for the single resource, doing (new BookingResource($timeSlot))->toArray(null); worked for me
When you pass null it remove the outer array for your to have an easy access to your objects

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.