In this tutorial you will learn about the How to SortBy Collection in Laravel 8 and its application with practical example.
In this How to SortBy Collection in Laravel 8 tutorial I will show you how to sort laravel collection using laravel SortBy method. In this tutorial you will learn to use laravel sortby function to sort laravel collection. In this article I will share various example to use sortby method in laravel. In this example we will be using sortby() method to sort laravel collection by name, two fields, dates and relation.
Laravel SortBy() Method
The laravel SortBy() method is used to sorts the collection by given key.
How to SortBy Collection in Laravel 8
In this step by step tutorial I will demonstrate the use of laravel SortBy() method with example.
- Collection Sort By Name
- Collection Sort By Two Fields in Laravel
- Collection Sort By Date in Laravel
- Collection Sort By Count in Laravel
- Collection Sort By Relation in Laravel
Laravel Collection Sort By Name Example
In this example we will be using SortBy() method to sort laravel collection by name.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public function index() { $collection = collect([ ['id' => 1, 'name' => 'John', 'email' => 'john@gmail.com'], ['id' => 2, 'name' => 'Sam', 'email' => 'sam@gmail.com'], ['id' => 3, 'name' => 'Bilal', 'email' => 'bilal@gmail.com'], ['id' => 4, 'name' => 'Lisa', 'email' => 'lisa@gmail.com'], ['id' => 5, 'name' => 'Samuel', 'email' => 'samuel@gmail.com'] ]); $filterd = $collection->sortBy('name'); $filterd->all(); print_r($filterd); } |
Collection Sort By Two Fields in Laravel
In this example we will be using SortBy() method to sort laravel collection by two fields.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public function index() { $collection = collect([ ['id' => 1, 'name' => 'John', 'email' => 'john@gmail.com'], ['id' => 2, 'name' => 'Sam', 'email' => 'sam@gmail.com'], ['id' => 3, 'name' => 'Bilal', 'email' => 'bilal@gmail.com'], ['id' => 4, 'name' => 'Lisa', 'email' => 'lisa@gmail.com'], ['id' => 5, 'name' => 'Samuel', 'email' => 'samuel@gmail.com'] ]); $filterd = $collection->sortBy(function ($data, $key) { return $data['name'].$data['email']; }); $filterd->all(); print_r($filterd); } |
Collection Sort By Date in Laravel
In this example we will be using SortBy() method to sort laravel collection by date.