Laravel | Collection(array) sortBy Method Example
Hello Dev,
Laravel provide many collection method in this tutorial we are learn sortBy method. sortby method use for sort array by value. sortby method sort array in ascending order. and sortByDesc() method sort array in descending order.
in this example we ar sort array by column or key name.
sortBy Key Value Example
public function index()
{
$collection = collect([
['name' => 'Shoes', 'price' => 1500],
['name' => 'Cap', 'price' => 500],
['name' => 'Shirt', 'price' => 900],
['name' => 'Pant', 'price' => 1000],
]);
$sorted = $collection->sortBy('price');
$sorted->all();
dd($sorted);
}
Output:
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[1] => Array
(
[name] => Cap
[price] => 500
)
[2] => Array
(
[name] => Shirt
[price] => 900
)
[3] => Array
(
[name] => Pant
[price] => 1000
)
[0] => Array
(
[name] => Shoes
[price] => 1500
)
)
)
- How to Notifications With database Driver in Laravel 11?
- How to Send Email Via Notification in Laravel 11?
- How to Install and Configure Laravel 11 Debugbar?
- How to Like Dislike System in Laravel 11?
- How to Paginate a Model with Relationship in Laravel 11?
- Laravel 11 Upload Files to Amazon S3 Example
- Laravel 11 Send WhatsApp Messages Example
- Laravel 11 Rest API Authentication Using JWT Tutorial