user6721269
user6721269

Reputation:

Getting records for the previous calendar month

I am trying to get the records of the previous month. That is say we are in February - I'd want to get records from 1st January to 31st January.

I tried:

$approved_reviews_lastMonth = ReviewHeader::where('created_at', '=', Carbon::now()->subMonth(1))->count();

But this does not get any for the last month.

Anyone?

Upvotes: 0

Views: 107

Answers (2)

Dilip Hirapara
Dilip Hirapara

Reputation: 15296

You can use whereBetween as well.

$firstDayofPreviousMonth = Carbon::now()->startOfMonth()->subMonth()->toDateString();
$lastDayofPreviousMonth = Carbon::now()->subMonth()->endOfMonth()->toDateString();
$approved_reviews_lastMonth = ReviewHeader::whereBetween('created_at', [$firstDayofPreviousMonth,$lastDayofPreviousMonth])->count();

Upvotes: 0

TsaiKoga
TsaiKoga

Reputation: 13394

Use format() to get the Year-Month format, and use like to get the previous month count.

$approved_reviews_lastMonth = ReviewHeader::where('created_at', 'like', Carbon::now()->subMonth(1)->format("Y-m")."%")->count();

Upvotes: 1

Related Questions