use Carbon\Carbon;
$dateFrom = Carbon::now()->subDays(30);
$dateTo = Carbon::now();
$total = DB::table('orders')
->whereBetween('created_at', [$dateFrom, $dateTo])
->groupBy('created_at')
->sum('billing_totalprice');
// Or using the Order model
$total = Order::whereBetween('created_at', [$dateFrom, $dateTo])
->groupBy('created_at')
->sum('billing_totalprice');
Nope :( I have this array:
I have sum for first 2, beacuse it have same time, anyway I want to show me array of all 30 days, and for the days where I dont hvae order to show me total price: 0.
$orders = DB::table('orders')
->select('created_at', DB::raw('SUM(billing_totalprice) AS total_price'))
->whereBetween('created_at', [$dateFrom, $dateTo])
->groupBy(DB::raw('DATE(created_at)'))
->get();
Now I have error:
SQLSTATE[42000]: Syntax error or access violation: 1055 '.orders.created_at' isn't in GROUP BY (SQL: select `created_at`, SUM(billing_totalprice) AS total_price from `orders` where `created_at` between 2020-03-06 12:08:29 and 2020-04-05 12:08:29 group by DATE(created_at))
I think the last query you used is fine but I'm guessing that your database may not contain a record for each day, meaning you'll get less than 30 days.
You should build that result after the request, it will be much easier than trying to do that within a SQL query.
You could use the CarbonPeriod API to loop on each day and populate the date with the matching record.
Thanks for the suggestion, but I wouldn't know how to do it. I'll try to click something for me.
I was wondering if it could be done with the SQL function. I guessed that I should looped on. I've been trying to do some solutions already, but I'm not succeeding.