Skip to content
Advertisement

Laravel Eloquent Select Between current month and previous 3 months

i’m trying to build a query that will select all of the records in my DB between now (current month) and the previous 3 months.

My query somewhat works, but i want to ignore the day of the month. At the moment, it’s selecting the last # of months to the current DAY as well but i want to ignore the current day and use the start and end of the months.

Here’s my query:

$dateS = Carbon::now()->subMonth(3);
$dateE = Carbon::now(); 
$TotalSpent = DB::table('orders')
->select('total_cost','placed_at')
->whereBetween('placed_at',[$dateS,$dateE])
->where(['deleted' => '0', 'delivery_address_id' => $DeliveryAddress->id])
->sum('total_cost');

Any help would be appreciated. It’s really bugging me!

Advertisement

Answer

This will do the trick I guess

$dateS = Carbon::now()->startOfMonth()->subMonth(3);
$dateE = Carbon::now()->startOfMonth(); 
$TotalSpent = DB::table('orders')
->select('total_cost','placed_at')
->whereBetween('placed_at',[$dateS,$dateE])
->where(['deleted' => '0', 'delivery_address_id' => $DeliveryAddress->id])
->sum('total_cost');

startOfMonth() begins with 1st date of the month

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement