How to sort array of objects in laravel?

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

How to sort array of objects in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by lindsey.homenick , 3 months ago

@scotty_walker 

In Laravel, you can sort an array of objects using the sortBy method. The sortBy method sorts the collection by the given key.


Here is an example of how you can sort an array of objects in Laravel:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$objects = [
    (object) ['name' => 'John', 'age' => 30],
    (object) ['name' => 'Alice', 'age' => 25],
    (object) ['name' => 'Bob', 'age' => 40],
];

$sortedObjects = collect($objects)->sortBy('age')->values()->all();

// Output the sorted objects
dd($sortedObjects);


In this example, the array of objects is sorted by the age key. The values() method is used to reset the keys of the collection after sorting.


You can also sort the objects in descending order by using the sortByDesc method:

1
$sortedObjects = collect($objects)->sortByDesc('age')->values()->all();


This will sort the array of objects by the age key in descending order.