Order By Relationship Count

Often, we need to use database-level ordering before we retrieve our records and fetch them to models. But also, in some cases, we need to perform the order a bit differently, for example counting the related models.

Let’s say we have a Post model and a Comment model. The Comment model has a belongsTo() relationship with the Post, while the Post has a hasMany() relationship with the comment.

Let’s say we need to order the posts based on how many comments they have. Fortunately, Laravel offers a simple, yet very powerful solution for this issue. Let’s see:

Post::orderBy('comments_count')->get();
Note, the Post model does not have the comments_count field at all. This is handled by Laravel behind the scenes.
Need a web developer? Maybe we can help, get in touch!