Scroll To Top

How to Query Posts by Different Dates in Laravel 5

Posted in Code, Database3 months ago • Written by Hujjat Nazari3 Comments

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.

How to Query Yesterday’s Posts

How to Query this week’s Posts

 How to Query this Month Posts

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.

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. 🙂

 


TAGS: , , , , ,

3 Comments so far. Feel free to join this conversation.

  1. robertMay 2, 2017 at 8:30 am - Reply

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

  2. Hujjat NazariMay 2, 2017 at 5:38 pm - Reply

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

    $currentMonth = date(‘m’);

  3. robertMay 8, 2017 at 12:32 pm - Reply

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

    maybe others need this piece of code.

Leave A Response