1

I'm adding an property to an object, and in this property I want to add different objects.

Code:

            // For each room grab the pins.
            foreach($rooms as $room) {

                // Grab all inspiration_id's for a specific room.
                $pins = Pins::where('room_id', $room['id'])->get();

                // Inspirations array.
                $inspirations = array();


             // For each pin use inspiration_id to grab inspiration id.
                foreach($pins as $pin) {

                    // Grab inspiration that matches the pin.
                    $pin = Inspirations::where('id', $pin['inspiration_id'])->get();

                    // Add a $pin to the array.
                    array_push($inspirations, $pin);

                }

                // Input inspirations into pins of this room.
                $room['pins'] = $inspirations;

            }

Example of current output below: enter image description here

The problem is: I want an inspiration to be added to pins as an object, now there is still an extra array around each inspiration. I really want to achieve the below result: Instead of what is shown in the image.

pins [
   {
     id: 1,
     ...
   },
   {
     id: 2,
     ...
   }
]
1
  • Right way is to use Relations. Read the docs. Commented Jul 11, 2018 at 15:31

1 Answer 1

1

Inspirations::where('id', $pin['inspiration_id'])->get(); returns an array. As id maybe the unique key, so try this

$pin = Inspirations::where('id', $pin['inspiration_id'])->first();

If id is the primary key, then make it simple

$pin = Inspirations::find($pin['inspiration_id']);
Sign up to request clarification or add additional context in comments.

Comments

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.