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

martinszeltins's avatar

Is there a way to sort a Collectin using sortBy($key, 'asc/desc')?

I noticed that the sortBy (orderBy) methods are a little bit different on Collection than on Query Builder, I'm not sure why that is. It seems more difficult to sort a collection by a key since it does not accept a second argument for asc/desc.

I would love to be able to sort by collection like this but I can't.

    $order = 'desc';
    $sorted = $collection->sortBy($company->user->id, $order)

But instead I have to do it this way. (As far as I know).

    $sorted = $collection ->sortBy(function ($item) {
        return $item->company->user->id;
    })

So... is it possible to sort like with the first (much shorter) method?

And is it possible to specify the order of 'asc/desc' without doing a if/else like this...

    if ($order == 'asc') {
        $sorted = $collection ->sortBy(function ($item) {
            return $item->company->user->id;
        })
    } else if ($order == 'desc') {
        $sorted = $collection ->sortByDesc(function ($item) {
            return $item->company->user->id;
        })
    }
0 likes
5 replies
Vilfago's avatar

No, and, no. Unfortunately.

SortBy is a sort on an object (the collection).

OrderBy is an injonction to your database engine to sort the result before sending them to your backend. This is far more powerful and efficient to sort your data at this level, as database engine are optimized for this work (if you use index on the relevant column).

martinszeltins's avatar

@REALRANDYALLEN - But I still need to check if the $order is == 'asc' or 'desc' and do sortBy or sortByDesc instead of passing it as second argument?

realrandyallen's avatar

@MARTINZELTIN - I jumped the gun on your question and deleted my response to respond better...so, while not exactly pretty you could technically do this:

$sortMethod = 'sortBy'; // or sortByDesc

$sorted = $collection->{$sortMethod}(function ($item) {
    return $item->company->user->id;
});
1 like
Insperio's avatar

I was in the middle of writing similar thing like @realrandyallen . Variable functions for the rescue

$o = ($order == 'asc') ? 'sortBy' : 'sortByDesc';

$sorted = $coll->$o(function ($item) {
return $item;
});
1 like

Please or to participate in this conversation.