Hello Devs,
In this tutorial, we will learn Laravel Collection SortBy and SortByDesc Method Example
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.
Follow this step by step guide below.
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
]
]
May this example help you.