Steve Steve - 2 months ago 13
SQL Question

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?

Answer

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