Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Jeyziii's avatar

Retrieve post using date and time

Help! I want to publish a post at a given date and time and remove it at a given date and time also. I tried both codes but it does not work. When I use only "whereDate" it it works fine, but when I added the "whereTime" It doesn't work. I need to do it with time. Also

$latest_article=Article::whereDate('published_at', '<=', Carbon::now())
                                ->WhereDate('expired_at', '>', Carbon::now())
                                ->whereTime('published_at', '<=', Carbon::now())
                                ->WhereTime('expired_at', '>', Carbon::now())
                                ->Where('status', 1)
                                ->latest()
                                ->limit(3)
                                ->get();
$latest_article=Article::whereDate('published_at', '<=', Carbon::now())
								->whereTime('published_at', '<=', Carbon::now())
                                ->WhereDate('expired_at', '>', Carbon::now())
                                ->WhereTime('expired_at', '>', Carbon::now())
                                ->Where('status', 1)
                                ->latest()
                                ->limit(3)
                                ->get();
0 likes
2 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

It looks like you're trying to use Carbon to filter the Article model by published_at and expired_at dates and times. The issue with your code is that you're using the whereDate and whereTime methods together, but these methods are designed to work on a date or time column, respectively.

Instead of using the whereDate and whereTime methods, you can use the where method to filter the Article model by the published_at and expired_at columns. The where method allows you to specify a custom comparison operator, so you can use it to compare the published_at and expired_at columns to the current date and time.

Here's an example of how you could use the where method to filter the Article model:

$latest_article = Article::where('published_at', '<=', Carbon::now())
                         ->where('expired_at', '>', Carbon::now())
                         ->where('status', 1)
                         ->latest()
                         ->limit(3)
                         ->get();

This code will retrieve the three most recently published articles that have a published_at date and time that is less than or equal to the current date and time, and an expired_at date and time that is greater than the current date and time.

1 like
Jeyziii's avatar

@Sinnbeck Thankyou very much! I though I needed to use the whereDate and whereTime, because it is a timestamp.

Please or to participate in this conversation.