ホーム > Laravel > Points to be aware of when using whereMonth in Laravel and how to retrieve data for the current month
Laravel

Points to be aware of when using whereMonth in Laravel and how to retrieve data for the current month

Thank you for your continued support.
This article contains advertisements that help fund our operations.

⇨ Click here for the table of contents for Laravel articles

I tried to summarize the points to be aware of when using whereMonth in Laravel and how to use it.

whereMonth does not mean "this month"

whereMonth is a function to retrieve data for a specific month, for example, "April."

Therefore, for example,

2022/04
2021/04
2020/04

all data for April in each year will be retrieved.

Therefore, it should not be used when you want to retrieve data specifically for "this month."

How to retrieve data for the current month in Laravel

There are various ways to do this, but here is one example.

use Carbon\Carbon;

$today = Carbon::now()->format('Y-m');
$start = $today.'-01 00:00:00';
$end = $today.'-31 23:59:59';
$posts = Post::where('created_at','>',$start)
          ->where('created_at','<',$end)
          ->get();

Explanation

By using where to retrieve data from

2022-04-01 00:00:00 to

2022-04-31 00:00:00

it is possible to achieve the desired result.

However, please use this method with caution as it is a bit of a workaround.

Conclusion

That's all.

If you have a better way of doing this, please let me know!

I hope this can be helpful to someone.

For feedback or complaints, please contact me via TwitterDM.

That's it!

Popular Articles

Deploying PHP7.4 + Laravel6 Project to AWS EC2

Implementing Breadcrumbs in Laravel using laravel-breadcrumbs

Please Provide Feedback
We would appreciate your feedback on this article. Feel free to leave a comment on any relevant YouTube video or reach out through the contact form. Thank you!