Basic Bridge
Basic Bridge

Reputation: 1911

Group and order by Day

I want to group posts by each day using eloquent

SQL table looks like this

+----+-------+------+------------+------------+
| id | title | slug | created_at | updated_at |
+----+-------+------+------------+------------+

If I use this code,

$links = Post::select(DB::raw('DAY(created_at) day, COUNT(*) post_count'))
    ->groupBy('day')
    ->orderBy('day', 'desc')
    ->get()

I get output as shown in below image, but it is only showing the number ( count ) of post on each day and not the post(s) individually.

enter image description here

So how can I get each post group each post by day.

Upvotes: 2

Views: 158

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219938

You should call the collection's groupBy method on the result:

$links = Post::selectRaw('DAY(created_at) day')->latest('day')->get();

$links = $links->groupBy('day');

Upvotes: 1

Related Questions