How to sort data in a collection in laravel?

Member

by shyann , in category: PHP Frameworks , 3 months ago

How to sort data in a collection in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 3 months ago

@shyann 

In Laravel, you can sort the data in a collection using the sortBy method.


Here is an example of how you can sort a collection of users by their "name" attribute:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$users = AppUser::all();

$sortedUsers = $users->sortBy('name');

//You can also specify the sorting order as a second parameter, for example:
//$sortedUsers = $users->sortBy('name', SORT_DESC);

//You can then loop through the sorted collection as usual
foreach ($sortedUsers as $user) {
    echo $user->name;
}


Alternatively, you can use the sortByDesc method to sort the data in descending order:

1
$sortedUsers = $users->sortByDesc('name');


You can also use the sortBy method with a closure to sort the collection based on a custom function or attribute:

1
2
3
$sortedUsers = $users->sortBy(function ($user) {
    return $user->name;
});


These are some of the ways you can sort data in a collection in Laravel.