0

I have posts and comments tables in my database. Comments table has posts id as foreign key. Now if I want to sort posts with most comments, how can i do that in laravel?

yasaryousuf
  • 89
  • 2
  • 8

1 Answers1

8

This sorts the post by their comment count.

$posts = Post::withCount('comments')
    ->orderBy('comments_count', 'desc')
    ->get();
Sandeesh
  • 11,486
  • 3
  • 31
  • 42