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

lat4732's avatar
Level 12

Getting all the posts in the last 2 days when having a published_at column

We're having a website that has posts in it and each post have a created_at and published_at values. created_at column is storing the actual date & time when the post is being inserted to the database. published_at is either null or a date & time which helps me determine whether the post is scheduled for a publish in the future or the post is immediately published. How can I get all the records from the last 2 days when having these 2 columns? I tried with

Post::where(function($query) {
                            $query->where('created_at', '>=', now()->subDays(2))
                                  ->orWhere('published_at', '>=', now()->subDays(2))
                                  ->orWhereNull('published_at');
                        })->get();

but it's not the expected output.

0 likes
3 replies
MohamedTammam's avatar
Post::where('created_at', '>=', now()->subDays(2))
->where(function($query) {
  $query->where('published_at', '>=', now()->subDays(2))
        ->orWhereNull('published_at');
})->get();
1 like
lat4732's avatar
Level 12

@MohamedTammam But it's also showing the future posts and it doesn't needs to. I need to add some condition inside the

->where(function($query) {
  $query->where('published_at', '>=', now()->subDays(2))
        ->orWhereNull('published_at');
})

to apply only when published_at is set maybe?

MohamedTammam's avatar
Level 51

@Laralex Limit it.

->where(function($query) {
    $query->where('published_at', '>=', now()->subDays(2))
        ->where('published_at', '<=', now())
        ->orWhereNull('published_at');
})

Please or to participate in this conversation.