How to Query Posts by Different Dates in Laravel 5

Laravel 5 is the most popular PHP Framework. Developing php application is easy, fast and enjoyable with Laravel. In this tutorial you will learn Laravel 5 query posts by dates tips and tricks. You will learn how to query today’s post; how to query this week’s post and this months posts. This tutorial is going to short and show you the simple techniques for query posts by different dates.

Laravel 5 Query Posts by Dates

Laravel uses Carbon class date and time builder. You can learn more here about Carbon. As we promise to make this tutorial as short as possible, let’s start coding.

How to Query Today’s Posts

We assume you have a Post model and a created_at field in posts table of your database.

$today_posts = App\Post::whereRaw('Date(created_at) = CURDATE()')->get();

How to Query Yesterday’s Posts

$yesterday_posts = App\Post::whereRaw('Date(created_at) = DATE_ADD(CURDATE(), INTERVAL -1 DAY)')->get();

How to Query this week’s Posts

$weekly_posts = App\Post::whereBetween( 'updated_at', [Carbon::today()->startOfWeek(), Carbon::today()->endOfWeek()] )->get();

 How to Query this Month Posts

$currentMonth = date('m');
$weekly_posts = App\Post::whereRaw('MONTH(created_at) = ?',[$currentMonth])->get();

You might probably ask;

Why should I learn Laravel 5 query posts by dates and when can I use it?

You don’t need to query posts only. There are many situations where you want to compare today’s post count with yesterday’s posts. Or maybe you want to count today’s sold product and yesterday’s or this week or current month. So, this technique will be quite helpful in those types of applications.

How to Count Today’s Posts

Here is an small tips for counting today’s orders and you can use it to count other things as well.

$countTodayOrders = App\Order::whereRaw('Date(created_at) = CURDATE()')->count();

All you need to do is to replace the last get() function with count() function.

Conclusion

We hope you have learned something new and use it in your next project to create something cool and inspiring. If you have any questions, feel free to comment it bellow.  We will answer as soon as possible. 🙂

 

Coding TipsHow tolaravelLaravel 5Laravel Frameworktips and tricks
Comments (4)
Add Comment
  • robert

    When i try to get monthly posts count number will return this error: Undefined variable: currentMonth

  • Hujjat Nazari

    Hi,
    make sure you have added the varibale currectMonth above your query.

    $currentMonth = date(‘m’);

  • robert

    i fixed it with carbon $monthy_posts = Post::whereRaw('MONTH(created_at) = ?', Carbon::today()->month)->count();

    maybe others need this piece of code.

  • Aimal Amiri

    It was helpful thank you so much