sort() and sortBy()

Sort collections by value or by a specific key.

Syntax$collection->sortBy('key');

The sort() method sorts a collection of simple values. For collections of arrays or objects, use sortBy() and give it the key to sort on. Use sortByDesc() for descending order.

Sorting preserves the original keys, so chain values() to re-index.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A leaderboard endpoint sorts a collection of user scores in descending order before returning the top-ten results.
  • A product listing sorts items by price ascending so budget-conscious shoppers see the cheapest options first.
  • A task manager sorts a collection of to-do items first by priority then by due date to render the most urgent work at the top.

More examples

Sort a flat collection of numbers

sort() and sortDesc() order a flat collection of scalars in ascending and descending order respectively.

Example · php
$scores = collect([42, 7, 99, 15, 55]);

$asc  = $scores->sort();         // [7, 15, 42, 55, 99]
$desc = $scores->sortDesc();     // [99, 55, 42, 15, 7]

Sort by a specific key

sortBy() accepts a key name and reorders the collection so the item with the lowest 'price' comes first.

Example · php
$products = collect([
    ['name' => 'Chair',  'price' => 149],
    ['name' => 'Desk',   'price' => 399],
    ['name' => 'Lamp',   'price' =>  49],
]);

$cheapest = $products->sortBy('price');
// Lamp => 49, Chair => 149, Desk => 399

Multi-column sort with a callback

Passes an array of [key, direction] pairs to sortBy() to achieve a stable multi-column sort.

Example · php
$tasks = Task::all()->sortBy([
    ['priority', 'desc'],
    ['due_at',   'asc'],
]);
// Highest priority first; ties broken by earliest due date

Discussion

  • Be the first to comment on this lesson.