Zach Tackett
Zach Tackett

Reputation: 614

Laravel: Iterate over object array

Ok, so I have an array of objects created in my controller

$displayRooms[$room] = $this->getNextEvent($events, $room);

return view('schedule')->with(['displayRooms' => $displayRooms]);

Then in my view, I am able to iterate over the array and get the $room and $events

@foreach ($displayRooms as $room => $events)
    {{ var_dump($events) }}
@endforeach

The var_dump($events) produces

/home/vagrant/sites/google-cal/storage/framework/views/96faa8d8afe2e0f07db5d96a536009499a3c48a5.php:22:
object(stdClass)[176]
  public 'available' => boolean false
  public 'room' => string 'Room 318' (length=8)
  public 'summary' => string 'Chem 3090 Himmeldirk' (length=20)
  public 'startTime' => string '12:00pm' (length=7)
  public 'endTime' => string '3:00pm' (length=6)
  public 'startDay' => string '03/21/17' (length=8)
  public 'endDay' => string '03/21/17' (length=8)

/home/vagrant/sites/google-cal/storage/framework/views/96faa8d8afe2e0f07db5d96a536009499a3c48a5.php:22:null

/home/vagrant/sites/google-cal/storage/framework/views/96faa8d8afe2e0f07db5d96a536009499a3c48a5.php:22:null

/home/vagrant/sites/google-cal/storage/framework/views/96faa8d8afe2e0f07db5d96a536009499a3c48a5.php:22:
object(stdClass)[226]
  public 'available' => boolean false
  public 'room' => string 'Room 513 (Voinovich Room)' (length=25)
  public 'summary' => string 'Reynolds' (length=8)
  public 'startTime' => string '1:00pm' (length=6)
  public 'endTime' => string '3:00pm' (length=6)
  public 'startDay' => string '03/21/17' (length=8)
  public 'endDay' => string '03/21/17' (length=8)

My question is how can I iterate over the events object in Blade in order to access the properties of the object, so that I may pass them to a partial view?

Upvotes: 0

Views: 2744

Answers (1)

Dylan Hamilton
Dylan Hamilton

Reputation: 692

If I'm understanding what you are asking (and your data structure) properly, then this should work. You can iterate the array of event objects to access each one individually, and then iterate each individual one to access each individual property / value. This code should be nested within your first foreach (replace the dump with it).

@foreach($events as $event) 
    @foreach ($event as $prop => $value) 
        // do whatever with prop / values
    @endforeach
@endforeach

If you don't need to access each property / value of the object one at a time, then I would recommend this instead.

@foreach($events as $event)
    // do whatever with each event
    {{ var_dump($event->available) }}
@endforeach

Upvotes: 1

Related Questions