-1

To get the total number of orders by weekday, I use:

Order::select('*')
  ->get()
  ->groupBy(function($date) {
    return Carbon::parse($date->created_at)->format('l');
  });

What I would like to add is that it returns, per weekday, the count of the items that were ordered, which is a property on the Order model called item_count. I tried using sum() on the query but that doesn't work.

eskimo
  • 2,421
  • 5
  • 45
  • 81
  • 1
    Does this answer your question? [Laravel Eloquent: sum with groupBy](https://stackoverflow.com/questions/24887708/laravel-eloquent-sum-with-groupby) – szaman Dec 29 '21 at 13:28
  • No that gives `Call to a member function groupBy() on string`. Maybe because in my case the `groupBy` is a function? – eskimo Dec 29 '21 at 13:44

1 Answers1

0

This was the solution:

Order::select(
    DB::raw('DAYNAME(created_at) AS week_day'),
    DB::raw('WEEKDAY(created_at) as day'),
    DB::raw("SUM(item_count) as items_total")
  )
  ->orderBy('day')
  ->groupBy(DB::raw('DAYNAME(created_at)'))
  ->get();
eskimo
  • 2,421
  • 5
  • 45
  • 81