phparrayslaraveleloquenteager-loading

Isolate a flat array from the values in a column of an array of Laravel collections


My collection is instantiated using the following query: $ClassesCollection = Classes::with('Queue')->whereIn('user_course_id', UserCourse::select('id')->where('user_id', $user->id))->get();

$ClassesCollection returns the desired result. However, I only want the Queue results.

So I split it this way

$classes = [];

    foreach($ClassesCollection as $class){
        array_push($classes, $class->Queue);
    }

And now I have an array of collections, each holding arrays of Queues.

How can I iterate over these collections to display the content of each array of Queues separately in my view?

This is what $classes holds

array:10 [▼
  0 => Collection {#968 ▼
    #items: array:12 [▼
      0 => Queue {#841 ▶}
      1 => Queue {#842 ▶}
      2 => Queue {#843 ▶}
      3 => Queue {#844 ▶}
      4 => Queue {#845 ▶}
      5 => Queue {#846 ▶}
      6 => Queue {#847 ▶}
      7 => Queue {#848 ▶}
      8 => Queue {#849 ▶}
      9 => Queue {#850 ▶}
      10 => Queue {#851 ▶}
      11 => Queue {#852 ▶}
    ]
  }
  1 => Collection {#969 ▶}
  2 => Collection {#970 ▶}
  3 => Collection {#971 ▶}
  4 => Collection {#972 ▶}
  5 => Collection {#973 ▶}
  6 => Collection {#974 ▶}
  7 => Collection {#975 ▶}
  8 => Collection {#976 ▶}
  9 => Collection {#977 ▶}
]

And each Queue holds several attributes such as date and class_id. So what can I do to display the content of each Queue?

EDIT: I thought there would be a cleaner way but this is how I solved my problem for anyone who comes across this.

$count = 0;
foreach ($classes as $collection => $queue) {
    /*
    $count = count($queue) - 1;
    for ($i = 0; $i <= $count; $i++){
        echo $queue[$i]->date . "\n";
    }
    */
    foreach ($queue as $Q) {
        echo $Q->date . "\n";
    }
}

The commented-out code achieves the desired effect too.


Solution

  • Use pluck():

    $queues = $ClassesCollection->pluck('Queue')->flatten();