memele
6 months ago

How to sort posts by latest commented

Posted 6 months ago by memele

I have a One to Many relationship for a Post model and a Comments model. I want to sort posts by latest commented - if someone posts a new comment that post goes to the top of the page.

This is what I tried but I still don't get posts sorted by latest comment. What is the correct way to do this?

$latestComments = Post::with(['comments' => function ($q) {
      $q->orderBy('created_at', 'desc');
}])->get();

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