Laravel | Collection(array) sortBy Method Example

Laravel

Nicesnippets

418

22-04-2020


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

)

)

)

I hope it can help you...