Helper to retrive a users posts checking between multple dates.

Posted 1 year ago by eddieace


I have written a helper function to get all active posts from a user within a specific time span. The problem here is that the condition after orWhereBetween it does not include the user_id which result in getting posts from all users.

This would work if i only would like to check one date, but in this case I would like to check both ends_at and published at to get all active posts that touches a specific time span.

Here is my helper method in my User class.

My question is, how do I solve this?

public function activePosts($from, $to) {
    return $this->hasMany(Post::class)->whereBetween('ends_at', [$from, $to])
        ->orWhereBetween('published_at', [$from, $to])

And here is the query

select * from `posts` where `posts`.`user_id` = ? and `posts`.`user_id` is not null and `ends_at` between ? and ? or `published_at` between ? and ?

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up


Reply to

Use Markdown with GitHub-flavored code blocks.