Php – Complex Laravel 5 group by on collection

arraysgroupinglaravelPHP

I have a collection 'Event' that has a relation of 'Site' & 'Inspection'.

What I want to do is group all events for on 'Inspection Date' and then under this group the events by 'Site'.

I.E

  • Inspection Date (YYYY-MM-DD)
    • Site 1
      • Event Name
      • Event Name
    • Site 2
      • Event Name
  • Inspection Date (YYYY-MM-DD)
    • Site 1
      • Event Name

And once I have this grouping, I want to output an array like:

[
  'title => 'Site Name: Event Name, Event Name, Event Name', 
  'date' => 'YYYY-MM-DD'
]

This is well above my intelligence so any help will be appreciated! BTW I am using Postgresql so it seems I can only use groupBy on the id's?

I have attempted a few thing using groupBy() and map(), which seems to kinda get me somewhere but not sure how to proceed:

$events = $events->groupBy('inspection.id')->map(function($item){
    return $item->groupBy('site.id');
});

Best Answer

Assuming the structure (simplified to array):

$events = [
   'name' => 'event name',
   'inspection' => ['date' => ' ... '] // relation
   'site' => ['name' => ' ... ']       // relation

this is what you need:

$collection
   ->groupBy('inspection.date')
   ->map(function ($events, $date) { 
       return $events
          ->groupBy('site.name')
          ->map(function ($events, $site) use ($date) { 
               return [
                  'title' => $site_name.': '.$events->implode('name', ', '), 
                  'date' => $date
               ];
          }); 
   });