Ari Patel
Ari Patel

Reputation: 37

Laravel - Count by day of week

Let's say I have this database table called books:

+----+-----------+-------------+
| id | bookTitle | publishedOn |
+----+-----------+-------------+
| 1  | Red Rose  | 2019-09-21  |
+----+-----------+-------------+
| 2  | Dark Fury | 2019-09-22  |
+----+-----------+-------------+
| 3  | Morbid    | 2019-10-01  |
+----+-----------+-------------+
| 4  | Dark      | 2019-11-14  |
+----+-----------+-------------+
| 5  | Route A   | 2019-11-15  |
+----+-----------+-------------+

How would I use Laravel's Eloquent to group by week of year so that on week 45... I published 2 books and so on.

And dataset would return something like:

$weekCount = [
  '45' => 2,
  '46' => 1,
  '47' => 1,
  '48' => 2
];

Upvotes: 0

Views: 319

Answers (1)

TsaiKoga
TsaiKoga

Reputation: 13394

Use mysql WEEK(timestamp):

Group by week number with year:

$weekCount = [];
Book::selectRaw('WEEK(publishedOn) AS publishedWeek, COUNT(id) AS booksCount')
    ->where(...)
    ->groupBy("publishedWeek")
    ->get()
    ->map('publishedWeek', function($item) use ($weekCount) {
        $weekCount[$item->publishedWeek] = $item->booksCount;
    });

Group by week number without year:

$weekCount = [];
Book::selectRaw("CONCAT(YEAR(publishedOn), '/', WEEK(publishedOn)) AS publishedWeek, COUNT(id) AS booksCount")
    ->where(...)
    ->groupBy("publishedWeek")
    ->get()
    ->map('publishedWeek', function($item) use ($weekCount) {
        $weekCount[$item->publishedWeek] = $item->booksCount;
    });

Upvotes: 1

Related Questions