try
App\Tweet::with('likes')->orderBy('likes', 'desc')->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I'm looking for a more sophisticated version of orderBy(), where I can order by the result of basic arithmetic between two colums.
Specifically, in the laravel from scratch tutorial, we eagerloaded tweets withLikes(), and fortunately you can orderBy() the eagerloaded properties ->likes and ->dislikes:
App\Tweet::all()->withLikes()->orderBy('likes', 'desc'); //orders tweets by most likes to least likes
What I would like to do is orderBy( 'likes - dislikes', 'desc') //previous query but subtracting dislikes from likes
Is there an elegant way to do this? thanks for any advice!
You can use joins and orderByRaw
->orderByRaw('likes - dislikes DESC')
Something like this
App\Tweet::withLikes()
->join('like_model', 'tweets.id', '=', 'like_model.tweet_id')
->orderByRaw('like_model.likes - like_model.dislikes DESC')
->get();
I don't know your table names, so just change like_model to your table names and so on.
Please or to participate in this conversation.