devofash
devofash

Reputation: 328

GroupBy date with today's date on top

I've got a list of events grouped by start date (below works fine).

$events = Event::select('*')->orderBy('start_date', 'desc')->get()->groupBy(function($date) {
    return Carbon::parse($date->start_date)->format('dS F Y');
});

//current output
19/04/2018
    Event 1
    Event 2
18/04/2018
    Event 3
    Event 4
16/04/2018
    Event 5
    Event 6

What I'd like is, to show all events with today to be on top of the list (like below).

//desired output
18/04/2018
    Event 3
    Event 4
19/04/2018
    Event 1
    Event 2
16/04/2018
    Event 5
    Event 6

Would appreciate some help. Thanks in advance.

Upvotes: 1

Views: 44

Answers (2)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

Use this:

$today = Carbon::today()->format('dS F Y');
if($events->has($today)) {
    $events->prepend($events->pull($today), $today);
}

Upvotes: 1

rchatburn
rchatburn

Reputation: 752

This is a bit rough and more of an idea :-). I don't know how your data is structured and not really tested this etc but you can do this with collections, i've assumed that the date is the key if not you can do $item->date

1st create a collection that has all the events that are not todays date

$eventsExcludingToday = $events->filter(function ($item, $key) {
        return $key !== Carbon::now()->format('d/m/Y');
 });

2nd get the one that's todays date

$eventToday = $events->filter(function ($item, $key) {
        return $key === Carbon::now()->format('d/m/Y');
 })->first();

3rd put the date at the start of the collection we created first

$events = $eventsExcludingToday->prepend($eventToday);

Upvotes: 0

Related Questions