lucasvm1980
lucasvm1980

Reputation: 682

Laravel - Sum values between two dates

I need to sum values using Laravel db::table and get the result between two dates, example:

Date: 05/30/2016 Sold: 1 Date: 05/31/2016 Sold: 2

So result should be Sold: 3

This is a search result given by a filter by date, i have done something like this with no results:

DB::table('sales')
 ->where('date',$date_from)
 ->where('date',$date_to)
 ->selectRaw('sum(price)')
 ->selectRaw('id')
 ->groupBy('id')
 ->get(); 

Upvotes: 2

Views: 6392

Answers (3)

Aboudeh87
Aboudeh87

Reputation: 716

You should use whereBetween function, and I think you are using a wrong group by:

DB::table('sales')
        ->whereBetween('date', [$date_from, $date_to])
        ->groupBy('date')
        ->sum('price');

And if the date column's type is a `DATETIME, you should use:

->groupBy(DB::raw("DATE(date)"))

Upvotes: 1

D Coder
D Coder

Reputation: 572

You Should use whereBetween(), Try this one

DB::table('sales')
->whereBetween('date', [$date_from, $date_to])
->selectRaw('sum(price)')
->selectRaw('id')
->groupBy('id')
->get(); 

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

Use < and > to filter results by a date:

->where('date', '>', $date_from)
->where('date', '<', $date_to)

Or use whereBetween():

->whereBetween('date', [$date_from, $date_to])

Upvotes: 1

Related Questions