How to Sort A Collection In Laravel?

5 minutes read

In Laravel, you can sort a collection using the sortBy, sortByDesc, or sort methods.


The sortBy method sorts the collection by a given key in ascending order, while the sortByDesc method sorts the collection in descending order.


You can also use the sort method to sort the collection using a custom callback function.


For example, you can sort a collection of users by their name in ascending order like this:

1
$users = User::all()->sortBy('name');


Or you can sort the collection in descending order based on a specific attribute like this:

1
$users = User::all()->sortByDesc('created_at');


Alternatively, you can use the sort method with a custom callback function to sort the collection based on custom logic:

1
2
3
$sortedUsers = $users->sort(function($a, $b) {
    return $a->age <=> $b->age;
});


These methods provide flexibility and ease in sorting collections in Laravel.

Best PHP Cloud Hosting Providers in July 2024

1
DigitalOcean

Rating is 5 out of 5

DigitalOcean

2
AWS

Rating is 4.9 out of 5

AWS

3
Vultr

Rating is 4.8 out of 5

Vultr

4
Cloudways

Rating is 4.7 out of 5

Cloudways


What is the default sort order in Laravel collections?

The default sort order in Laravel collections is ascending order, meaning that the items in the collection will be sorted in alphabetical or numerical order from smallest to largest.


How to sort a collection in Laravel by multiple columns?

To sort a collection in Laravel by multiple columns, you can use the sortBy() or sortByDesc() methods along with a callback function.


Here's an example of sorting a collection by multiple columns:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$collection = collect([
    ['name' => 'John', 'age' => 30],
    ['name' => 'Jane', 'age' => 25],
    ['name' => 'Alice', 'age' => 35],
]);

$sortedCollection = $collection->sortBy([
    ['name', 'asc'],
    ['age', 'desc']
]);

$sortedCollection->values()->all();


In the example above, we have a collection of users with 'name' and 'age' attributes. We are sorting the collection first by 'name' in ascending order and then by 'age' in descending order.


You can use the sortByDesc() method for descending order sorting.

1
2
3
4
$sortedCollection = $collection->sortByDesc([
    ['name', 'asc'],
    ['age', 'desc']
]);


This will sort the collection by 'name' in ascending order and 'age' in descending order.


You can also use the with() method along with sortBy() or sortByDesc() for sorting by multiple columns in relationships.

1
2
3
4
5
6
$users = User::with('posts')->get();

$sortedUsers = $users->sortBy([
    ['name', 'asc'],
    ['posts.created_at', 'desc']
]);


In this example, we are sorting the collection of users by 'name' in ascending order and by the 'created_at' attribute of their related posts in descending order.


These are some ways you can sort a collection in Laravel by multiple columns.


How to sort a collection in Laravel by nested attributes?

To sort a collection in Laravel by nested attributes, you can use the sortBy method in combination with the -> operator to access nested attributes. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$collection = collect([
    [
        'id' => 1,
        'nested' => [
            'attribute' => 'value1'
        ]
    ],
    [
        'id' => 2,
        'nested' => [
            'attribute' => 'value2'
        ]
    ],
    [
        'id' => 3,
        'nested' => [
            'attribute' => 'value3'
        ]
    ]
]);

$sortedCollection = $collection->sortBy('nested.attribute');

$sortedCollection->all();


In this example, we have a collection with nested attributes. We use the sortBy method to sort the collection by the attribute key inside the nested array. The -> operator is used to access the nested attributes.


After calling sortBy('nested.attribute'), the collection will be sorted based on the value of the attribute key inside the nested array.


You can then use the all() method to retrieve the sorted collection as an array.


How to sort a collection in Laravel in descending order?

You can sort a collection in Laravel in descending order by using the sortByDesc method. Here is an example:

1
2
3
4
5
6
7
use Illuminate\Support\Collection;

$collection = collect([['name' => 'John'], ['name' => 'Jane'], ['name' => 'Bob']]);

$sortedCollection = $collection->sortByDesc('name');

$sortedCollection->all();


In this example, the collection is sorted by the name attribute in descending order. The sortByDesc method sorts the collection in descending order based on the specified attribute.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To sort an array in Swift, you can use the sort() or sorted() method. The sort() method sorts the array in place, while the sorted() method returns a new sorted array without modifying the original array. You can sort the array in ascending order by using the ...
In Laravel, you can sort records in alphabetical order by using the orderBy method in your query. For example, you can use the orderBy method on a query builder instance to sort records by a specific column in alphabetical order. Additionally, you can chain mu...
To sort a pandas dataframe in ascending order row-wise, you can use the sort_values() method along with the axis=1 parameter. This will sort the values in each row in ascending order.Here&#39;s an example of how you can sort a pandas dataframe named df row-wis...