This seemed to do the trick:
->leftJoin('ratings', function ($join) {
$join->on('ratings.book_id', '=', 'book.id')->where('ratings.user_id', '=', $this->user->id);
})
->orderBy('ratings.value', 'desc')
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Edit: Stand by...I think I figured it out. Will update shortly.
I got some very good help here (https://laracasts.com/discuss/channels/eloquent/id-like-to-return-all-books-in-a-users-collection-with-all-the-users-ratings) that is working great. The new thing that I've been struggling with for a couple hours is now ordering by that relationship field.
So, users can add books to their collection. They can then go to their user page and view their whole collection, along with all of the ratings they have added to books. That all works great. Now, I'd like to let them order by their own ratings. Problem is, the order by is taking into account all user's ratings. So if User1 rated 'The Great Gatsby' with a 7, and 'Invisible Man' a 7.5 and User2 rated 'The Great Gatsby' with an 8 - When User1 goes to view their collection and sort by ratings, it's going to put 'The Great Gatsby' above 'Invisible Man'.
Not sure how I can order by only the given user's ratings and not by all ratings in the table. This is what I have:
Book::with([
'images',
'ratings' => function ($query) {
$query->where('user_id', $this->user_id);
}])
->join('collections as c', 'c.book_id', '=', 'books.id')
->where('c.user_id', '=', $this->user->id)
->leftJoin('ratings', 'ratings.book_id', '=', 'books.id')
->orderBy('ratings.value', 'desc')
->paginate(20)
Also tried...
Book::with([
'images',
'ratings' => function ($query) {
$query->where('user_id', $this->user_id);
}])
->join('collections as c', 'c.book_id', '=', 'books.id')
->where('c.user_id', '=', $this->user->id)
->leftJoin('ratings', 'ratings.book_id', '=', 'books.id', 'and', 'ratings.user_id', '=', $this->user->id)
->orderBy('ratings.value', 'desc')
->paginate(20)
Please or to participate in this conversation.