How to search by month from a date in laravel?

Member

by shyann , in category: PHP Frameworks , 3 months ago

How to search by month from a date in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lottie , 3 months ago

@shyann 

To search by month from a date in Laravel, you can use the whereMonth method provided by Eloquent. Here is an example of how you can use it:

1
2
3
4
5
$month = 5; // Month to search for
$posts = Post::whereMonth('created_at', $month)->get();

// Or you can use whereRaw method to search by month
$posts = Post::whereRaw('MONTH(created_at) = ?', [$month])->get();


In this example, we are searching for posts where the created_at date field month is equal to 5 (May). You can replace the value of $month variable with the month you want to search for.