Steve
Steve

Reputation: 1672

Group By eloquent laravel

I have all the matches ordered by start_date, but i want the date not to be shown always instead separate the teams by date like below:

$matches=Match::orderBy('start_date','desc')->get();
foreach($matches as $match)
{
      $match->team1;
      $match->team2;
      $match->start_date;
}

this gives:

Team1
Team2 
2016-9-28
Team3
Team4 
2016-9-28
Team5
Team6 
2016-9-28
...

Instead I want

2016-9-28 
Team1
Team2 
Team3
Team4
Team5
Team6
....

2016-9-29
Team1
Team2
Team3
....

group_by start_date may be?

Upvotes: 0

Views: 8874

Answers (2)

Jason Seah
Jason Seah

Reputation: 1564

hmm.. you can try

$matches =  Match::select(DB::raw('GROUP_CONCAT(team) AS teammate'), 'start_date')
           ->groupBy('start_date');
           ->get()
           ->toArray();

toArray is optional and the result should be:

array:2 [
    0 => array:2 [
      "start_date" => "2016-9-28"
      "teammate" => "Team1,Team2, Team3, Team4, Team5, Team6"
    ]
    1 => array:2 [
      "start_date" => "2016-9-29"
      "teammate" => "Team1,Team2, Team3"
    ]
]

is this the result you seeking for ?

Upvotes: 1

chanafdo
chanafdo

Reputation: 5124

Use groupBy to group the resulting collection.

$matchGroups = Match::orderBy('start_date','desc')->get()->groupBy('start_date');

If start_date is a Carbon date you may try

$matchGroups = Match::orderBy('start_date','desc')->get()->groupBy(function($item) {
    return $item->start_date->format('Y-n-j');
});

And in your view

@foreach ($matchGroups as $startDate => $matches) {
    {{ $startDate }}

    @foreach ($matches as $match) {
        {{ $match->team1 }}
        {{ $match->team2 }}
    @endforeach
@endforeach

Upvotes: 3

Related Questions