Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

commish's avatar

Flexible alternative to orderBy()

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!

0 likes
5 replies
ousid's avatar

try

	App\Tweet::with('likes')->orderBy('likes', 'desc')->get();
MichalOravec's avatar
Level 75

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.

https://laravel.com/docs/7.x/queries#joins

2 likes
ousid's avatar

or you can make a method in App\Tweet Model like so:


    public static function OrderByLikes($order)
    {
        return self::withCount('likes')
        ->orderBy('replies_count', $order) // you can replace $order variable by 'desc' or 'asc' as you want
        ->take(5) // here if you want to limit the results in this example 5 or if you want you can remove it
        ->get(); // you can replace `get` method with `paginate` if you want to limit the result in each page
    }
	

and in you controller you can do this


$tweets = App\Tweet::orderByLikes('desc');

1 like
commish's avatar

orderByRaw worked super easily, I didn't even need the join():

$tweetsWithLikes->orderByRaw('likes - dislikes DESC')->get();

Please or to participate in this conversation.