Flobesst
Flobesst

Reputation: 1340

Laravel: group results by date

In my Laravel project, I have a Match model which contains the following fields: id and starting_at timestamp.

I would like to list all matches and group them by date, just like this:

1st of June:

  1. Match id 57
  2. Match id 87

2nd of June:

  1. Match id 40
  2. Match id 99

...

Thanks !

Upvotes: 1

Views: 1744

Answers (2)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

You need to return a collection and then group items by starting_at:

$matches = Match::all(); // or whatever constraints you want to apply
$matchesByDate = $matches->groupBy('starting_at');

Mind that SQL timestamp is not a valid array key, so if starting_at is such a field, then you need to change it a bit, for example:

$matchesByDate = $matches->groupBy(function ($match) { return substr($match->starting_at, 0, 10);});

Upvotes: 3

arrowill12
arrowill12

Reputation: 1804

this is not tested but should work....also you should probably split this up into a one to many relationship that would make this much easier.

  $matches = Matches::select('starting_at')->distinct()->get();
    foreach($matches as $match){
      echo $match->starting_at."<br/>";
      $ids =  Matches::where("starting_at",$match->starting_at)->lists('id');
      $count = 1;
      foreach ($ids as $id){
         echo $count.". Match id ".$id."<br/>";
         $count ++;
      }
   }

Upvotes: 0

Related Questions