1 year ago

How to sort posts by latest commented

Posted 1 year ago by divinulledivi

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');

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