How to get last month data using laravel? I want to retrieve data from last month that is equal to today's date.
ex: if today is 2022/02/08 I want to retrive data of 2022/01/08
Is there any way to do this with laravel?
I assume you mean data for all the days between those two dates?
MyModel::query()->whereBetween('created_at', [now(), now()->subMonth()])->get();
@Sinnbeck No just the specific date equal to today date.
as per example only data of 2022/01/08
@avishkaMe So like this?
MyModel::query()->whereDate('created_at', now()->subMonth())->get();
Just be aware that not all months have the same amount of days..
@Sinnbeck yeah but this query returns all records of last month. I only want the records of that specific day (ex: 2022/01/08)
@avishkaMe Did you test it? It should just get the records for the date one month ago
@Sinnbeck Oh my mistake this was the exact answer, I used the whereMonth instead of whereDate.
Thank you very much for this great help.
But as I mentioned. Be sure you plan out how you want to handle dates that goes beyond the 28th. Subtracting a month from 31. March 2022, might not give you want you expect :)
@Sinnbeck is there any way to retrieve records of date before 30 days from the current date?
@avishkaMe You can use ->subDays(30). But carbon will subtract 30 days if you are on day 29-31 I think.
@Sinnbeck yeah that was what I'm exactly looking for. I highly appreciate your help.
Please sign in or create an account to participate in this conversation.