Mehdi Yaghoubi
Mehdi Yaghoubi

Reputation: 643

How I can get total sum of daily values of a column in Laravel?

There is an orders table with a total column that has more than 1000 records. How I can get the daily sum of total for each day. I mean for Monday, Thursday, Wednesday, .... there are many and different rows, and I want to show the sum of total of each day separately? in UI as:

saturday: 111211,
sunday: 211444,
Monday: 120012000,
Thursday: 1225121,

Friday sales

Upvotes: 1

Views: 804

Answers (2)

Mehdi Yaghoubi
Mehdi Yaghoubi

Reputation: 643

I use ORM and this worked for me:

        $sales = Order::all()->groupBy(function ($date) {
            return $date->created_at->format('Y-m-d');
        })->map(function ($item) {
            return [
              "date" => item[0]->created_at,
              "total" => $item->sum('total'),
            ];
        });

Upvotes: 0

Imran Munawar
Imran Munawar

Reputation: 48

MySQL Query: SELECT DAYNAME(created_at) as day, SUM(total) as total FROM orders group by day

Laravel Query Builder:

DB::table('orders')
       ->selectRaw('DAYNAME(created_at) as day, SUM(total) as total')
       ->groupBy('day')
       ->get();

Upvotes: 3

Related Questions