ns in Laravel 12 using the sortBy() method. It helps you arrange items in ascending order based on a key or a callback function. I’ll walk you through different use cases, including simple values, nested keys, multiple columns, and date sorting with clear code examples.
How to sortBy Collection in Laravel 12
The sortBy() method in Laravel Collections lets you sort items in ascending order by a given key or a custom callback.
Example 1: Simple sortBy on a Key
$collection = collect([
['name' => 'Zara', 'score' => 60],
['name' => 'Alex', 'score' => 90],
['name' => 'John', 'score' => 75],
]);
$sorted = $collection->sortBy('score');
$sorted->values()->all();
// Output:
// [
// ['name' => 'Zara', 'score' => 60],
// ['name' => 'John', 'score' => 75],
// ['name' => 'Alex', 'score' => 90],
// ]
Example 2: sortBy Using Callback Function
$collection = collect([
['name' => 'Item 1', 'quantity' => 50],
['name' => 'Item 2', 'quantity' => 20],
['name' => 'Item 3', 'quantity' => 35],
]);
$sorted = $collection->sortBy(function ($item) {
return $item['quantity'];
});
$sorted->values()->all();
Example 3: sortBy Nested Key
$collection = collect([
['name' => 'Product A', 'details' => ['price' => 150]],
['name' => 'Product B', 'details' => ['price' => 100]],
['name' => 'Product C', 'details' => ['price' => 200]],
]);
$sorted = $collection->sortBy('details.price');
$sorted->values()->all();
Example 4: sortBy Date
$collection = collect([
['title' => 'Post 1', 'created_at' => '2024-05-01'],
['title' => 'Post 2', 'created_at' => '2024-04-15'],
['title' => 'Post 3', 'created_at' => '2024-06-10'],
]);
$sorted = $collection->sortBy('created_at');
$sorted->values()->all();
// Output will be sorted from oldest to newest
Example 5: sortBy Multiple Columns
You can use sortBy()
with multiple fields by returning a combined value in the callback:
$collection = collect([
['name' => 'John', 'score' => 90],
['name' => 'John', 'score' => 80],
['name' => 'Alice', 'score' => 95],
]);
$sorted = $collection->sortBy(function ($item) {
return $item['name'] . $item['score'];
});
$sorted->values()->all();
You might also like: