k0tkin's avatar

How to OrderBy recent most commented posts in a Forum

I'm working on a forum and I want to show the most commented posts in the past 2 days on the first page (with pagination)

I want to get all my posts with pagination but the posts in the past 2 days get sorted by comments_count

I have a 'comments_count' column in my posts table

This code is not what I want, I don't want to show posts that are 3-4 days old in the first page

$posts = Post::orderBy('comments_count', 'desc')->paginate(20);

This code is not what I want, I want all my posts not just past 2 days.

$posts = Post::where('created_at', '>', Carbon::now()->subDays(2))->orderBy('comments_count', 'desc')->paginate(20);
``
0 likes
5 replies
Nakov's avatar

Have you tried the updated_at column instead? If you increase the comments_count every time there is a new comment for your post, then the updated_at column is what is the latest:

$posts = Post::where('updated_at', '>=', Carbon::now()->subDays(2))
	->latest('updated_at')
	->orderBy('comments_count', 'desc')
	->paginate(20);
1 like
k0tkin's avatar

@Nakov Thank you for your answer I want to paginate all my posts but this code will get only "where('updated_at', '>=', Carbon::now()->subDays(2))" an issue with this answer is for example a 100 day old post with a big comments_count can get on top just with a new comment

Nakov's avatar

@k0tkin hm, yeah, that's right. But then only if you reverse the ordering it will work, but I am not sure if that again will be sufficient for your case:

$posts = Post::query()
	->orderBy('comments_count', 'desc')
	->latest()
	->paginate(20);

So this will first order by the comments_count and then by when it was created_at.

1 like
k0tkin's avatar

@Nakov But still it doesn't consider only the past 2 days posts

I'm thinking about something like this but I don't remember the exact code Basicaly I want to get all posts but sorting some of them conditionally

$posts = Post::orderBy(['comments_count' => function ($q) {
            $q->where('created_at', '>=', Carbon::now()->subDays(2));
        }])->paginate(20);
k0tkin's avatar

This is what I found but still doesn't work

        $posts = Post::orderByDesc(function ($query) {
            $query->select('comments_count')->where('created_at', '>', Carbon::now()->subDays(2));
        })->paginate(20);

Please or to participate in this conversation.