How to get sorted data from array in laravel?

by hal.littel , in category: PHP CMS , 18 days ago

How to get sorted data from array in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 17 days ago

@hal.littel 

In Laravel, you can use the sortBy() or sortByDesc() methods to sort an array of data.

  1. If you have a collection (i.e. a result set from the database), you can use the sortBy() method like this:
1
2
3
4
5
$collection = Model::all();

$sortedCollection = $collection->sortBy('column_name'); // Sort in ascending order
// OR
$sortedCollection = $collection->sortByDesc('column_name'); // Sort in descending order


  1. If you have an array of data, you can use the collect() helper function to convert it into a collection and then apply the sortBy() method. Here's an example:
1
2
3
4
5
$array = ['John', 'Jane', 'Alice', 'Bob'];

$sortedArray = collect($array)->sortBy();
// OR
$sortedArray = collect($array)->sortByDesc();


By using these methods, you can easily sort your data in Laravel.