Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Mick79's avatar

Return collection grouped by date

I've asked this question before and it didn't get resolved, but I'm pretty sure I asked the question terribly. Here's my second attempt.

I have a collection and I need to output that collection grouped by a given timeframe (by week initially then as the site gets busier by day).

Here is the code I'm using to get the collection:

$latest = Site::query()
                ->with('upvotes')
                ->where([
                    ['is_approved', '=', 2],
                    ['is_featured', '=', 1],
                ])->orderBy('created_at', 'DESC')
                ->get();

I have tried various different ways of doing a "group by" but I don't think that's the solution.

What I'm trying to achieve is to run an @foreach in the blade and have the results output like this

Today

- Item 1
- Item 2
- Item 3

Yesterday

- Item 1
- Item 2

2 days ago

Item 1
Item 2
Item 3

Etc Etc...

It's proving fairly challenging.

it seems to me like what I need to achieve is something along the lines of

@foreach($dates as $date)

    {{$date->diffForHumans()}}
    
    @foreach($date->items as $item)
        $item->name
        $item->description
    @endforeach

@endforeach

But I don't know, or can't figure out how to get there.

All help appreciated.

0 likes
4 replies
Tangente's avatar
Tangente
Best Answer
Level 9

Try this method:

use Carbon\Carbon; $latest = Site::query() ->with('upvotes') ->where([ ['is_approved', '=', 2], ['is_featured', '=', 1], ])->orderBy('created_at', 'DESC') ->get() ->groupBy(function($date) { return Carbon::parse($date->created_at)->format('D'); // grouping by days

});

Mick79's avatar

Holy sh1t that seems to produce the collection as I need it! However I'm getting an error "Property [upvotes] does not exist on this collection instance"

however if I dd $latest I can see that the upvotes relation is still in there, but possibly one layer deeper than it was before?

Thanks @daniyum21 - how would I output that in the blade to be structured as I need it?

Mick79's avatar

@daniyum21 previously I would access the data with

$product->site_name

however now that isn't working for example I'm getting this error

Property [site_screengrab] does not exist on this collection instance.

however if I do this

$product[0]->site_name

it works. I can't replace that "0" with a variable and increment it either as that will obviously fail.

Please help :-)

Mick79's avatar

It's cool I sorted it. I needed to do a foreach inside the foreach. Which I already knew I would need to do.... D'oh!

Please or to participate in this conversation.