I have 2 tables in my database.
books and ratings
books
ratings
in books id, name
id
name
in ratings
You can use a modified withCount():
withCount()
$books = Book::withCount(['ratings as average_rating' => function($query) { $query->select(DB::raw('coalesce(avg(rating),0)')); }])->orderByDesc('average_rating')->get();