How to sort data in a collection in laravel?

Member

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

How to sort data in a collection in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 9 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.

Related Threads:

How to sort a collection in laravel?
How to sort laravel collection by distance from location?
How to sort product collection in shopify?
How to sort data in MongoDB using PHP?
How to sort data from highest to lowest in chart.js?
How to get data from collection map in discord.js?