Laravel Collection SortBy and SortByDesc Method Example

Laravel 6 , Laravel , Laravel 7

Nicesnippets

3968

15-01-2020


Hi Guys,

In this example,I will learn you how to use collection sort by method in laravel.you can simply ans easy to use sort(),sortBy and SortByDesc() in laravel.

Laravel Collection object provide several methods that will help to write your own logic. here we will learn how to use sort method of laravel collection.

In this example,i will give you simple array collection object then convert to sorting order collection.other multidimensional array collection object then convert to asending and descding order to array.bellow Example

Example 1: sort()


public function index()

{

$collection = collect([5, 3, 1, 2, 4]);

$sorted = $collection->sort();

dd($sorted);

}

Output :

#items: array:5 [?

2 => 1

3 => 2

1 => 3

4 => 4

0 => 5

]

Example 2: SortBy()

public function index()

{

$myStudents = [

['id'=>1, 'name'=>'Hardik', 'mark' => 80],

['id'=>2, 'name'=>'Paresh', 'mark' => 20],

['id'=>3, 'name'=>'Akash', 'mark' => 34],

['id'=>4, 'name'=>'Sagar', 'mark' => 45],

];

$myStudents = collect($myStudents);

$sorted = $myStudents->SortBy('name');

dd($sorted);

}

Output :

#items: array:4 [?

2 => array:3 [?

"id" => 3

"name" => "Akash"

"mark" => 34

]

0 => array:3 [?

"id" => 1

"name" => "Hardik"

"mark" => 80

]

1 => array:3 [?

"id" => 2

"name" => "Paresh"

"mark" => 20

]

3 => array:3 [?

"id" => 4

"name" => "Sagar"

"mark" => 45

]

]

Example 3: SortByDesc()

public function index()

{

$myStudents = [

['id'=>1, 'name'=>'Hardik', 'mark' => 80],

['id'=>2, 'name'=>'Paresh', 'mark' => 20],

['id'=>3, 'name'=>'Akash', 'mark' => 34],

['id'=>4, 'name'=>'Sagar', 'mark' => 45],

];

$myStudents = collect($myStudents);

$sorted = $myStudents->SortByDesc('name');

dd($sorted);

}

Output :

#items: array:4 [?

3 => array:3 [?

"id" => 4

"name" => "Sagar"

"mark" => 45

]

1 => array:3 [?

"id" => 2

"name" => "Paresh"

"mark" => 20

]

0 => array:3 [?

"id" => 1

"name" => "Hardik"

"mark" => 80

]

2 => array:3 [?

"id" => 3

"name" => "Akash"

"mark" => 34

]

]

It will help you....


Recommended Posts