Laravel Collection Sort By Multiple Fields Example

By Hardik Savani November 7, 2023 Category : Laravel

Hello Artisan,

In this example, I will show you laravel collection sort by multiple fields. you can understand a concept of laravel collection order by multiple columns. I would like to show you laravel collection sortby multiple columns. We will look at an example of how to sortby multiple fields in laravel collection. follow the below step for sortby multiple columns larave

Laravel provides sortBy() method to sort multiple fields in collection. sortBy() method accept array argument to order by multiple column in collection. here, i will give you two examples. so, let's see the examples:

Example 1:

you can see the below controller code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$collection = collect([

['id' => 1, 'name' => 'Hardik', 'age' => '32'],

['id' => 2, 'name' => 'Paresh', 'age' => '33'],

['id' => 3, 'name' => 'Ankit', 'age' => '33'],

['id' => 4, 'name' => 'Mahesh', 'age' => '30'],

]);

$sorted = $collection->sortBy(['age', 'name']);

$sorted = $sorted->all();

dd($sorted);

}

}

Output:

Array

(

[3] => Array

(

[id] => 4

[name] => Mahesh

[age] => 30

)

[0] => Array

(

[id] => 1

[name] => Hardik

[age] => 32

)

[2] => Array

(

[id] => 3

[name] => Ankit

[age] => 33

)

[1] => Array

(

[id] => 2

[name] => Paresh

[age] => 33

)

)

Example 2:

you can see the below controller code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$collection = collect([

['id' => 1, 'name' => 'Hardik', 'age' => '32'],

['id' => 2, 'name' => 'Paresh', 'age' => '33'],

['id' => 3, 'name' => 'Ankit', 'age' => '33'],

['id' => 4, 'name' => 'Mahesh', 'age' => '30'],

]);

$sorted = $collection->sortBy(function ($value) {

return $value['age'].'-'.$value['name'];

});

$sorted = $sorted->all();

dd($sorted);

}

}

Output:

Array

(

[3] => Array

(

[id] => 4

[name] => Mahesh

[age] => 30

)

[0] => Array

(

[id] => 1

[name] => Hardik

[age] => 32

)

[2] => Array

(

[id] => 3

[name] => Ankit

[age] => 33

)

[1] => Array

(

[id] => 2

[name] => Paresh

[age] => 33

)

)

I hope it can help you...

Shares