Order based on a related model's average or count

Did you ever need to order based on a related model's average or count?

It's easy with Eloquent!

1public function bestBooks()
2{
3 Book::query()
4 ->withAvg('ratings as average_rating', 'rating')
5 ->orderByDesc('average_rating');
6}

Tip given by @mmartin_joo

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord