Table of contents

laravel collection sort

In this post, you will learn how to implement Laravel collection sort if you are working with Laravel collection it needs to learn to sort also because sometimes we need to customize the ordering before we display it to the user end.

 

The Laravel collection sort has many ways as follows below:

  • sort()
  • sortBy()
  • sortByDesc()
  • sortDesc()
  • sortKeys()
  • sortKeysDesc()
  • sortKeysUsing()

 

Laravel collection sort()

The sort method will sort the collection and generate keys with sorted values. In this case, they keep the original array keys, so we need to use values method to reset keys consecutively numbered indexes.

 

public function index()
{
        $collection = collect(['c','b','d','a','e']);

        $collection = $collection->sort();

        print_r($collection->all());

        print_r($collection->values()->all());die;
}


//result

/*
without using values() with the original keys.
Array
(
    [3] => a
    [1] => b
    [0] => c
    [2] => d
    [4] => e
)
*/

/*
using values() to reset the keys.
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
)
*/

 

 

Laravel Collection sortBy()

In this section, we can able to sort with the specific key in collections using sortBy method.

public function index()
{
        $collection = collect([
            ['name' => 'John Doe', 'salary' => 1600],
            ['name' => 'Jane Dane', 'salary' => 2100],
            ['name' => 'Cardo Dalisay', 'salary' => 950],
        ]);

        $collection = $collection->sortBy('salary');

        print_r($collection->values()->all());die;
}

/*
result.

Array
(
    [0] => Array
        (
            [name] => Cardo Dalisay
            [salary] => 950
        )

    [1] => Array
        (
            [name] => John Doe
            [salary] => 1600
        )

    [2] => Array
        (
            [name] => Jane Dane
            [salary] => 2100
        )

)
*/

 

The sortBy method second argument allows us to pass PHP sort flags.

public function index()
{
        $collection = collect([
            ['name' => 'John Doe', 'salary' => 1600],
            ['name' => 'Jane Dane', 'salary' => 2100],
            ['name' => 'Cardo Dalisay', 'salary' => 950],
        ]);

        $collection = $collection->sortBy('name', SORT_NATURAL);

        print_r($collection->values()->all());die;
}

/*
Result.

Array
(
    [0] => Array
        (
            [name] => Cardo Dalisay
            [salary] => 950
        )

    [1] => Array
        (
            [name] => Jane Dane
            [salary] => 2100
        )

    [2] => Array
        (
            [name] => John Doe
            [salary] => 1600
        )

)


*/

 

Laravel collection sortBy() has an alternative option that we can pass our own closure to determine how we sort the collection's values.

 

Example #1: This will return the price same about and sort it.

public function index()
{
        $collection = collect([
            ['name' => 'Item 1', 'price' => 89],
            ['name' => 'Item 2', 'price' => 107],
            ['name' => 'Item 3', 'price' => 37],
        ]);

        $collection = $collection->sortBy(fn($item, $key) => $item['price']);

        print_r($collection->values()->all());die;
}

/*
Result.


Array
(
    [0] => Array
        (
            [name] => Item 3
            [price] => 37
        )

    [1] => Array
        (
            [name] => Item 1
            [price] => 89
        )

    [2] => Array
        (
            [name] => Item 2
            [price] => 107
        )

)

*/

 

Example #2: This will count the total values of variants key and sort them.

public function index()
{
        $collection = collect([
            ['name' => 'Item 1', 'variants' => ['blue', 'red']],
            ['name' => 'Item 2', 'variants' => ['green']],
            ['name' => 'Item 3', 'variants' => ['orange', 'yellow', 'blue']],
        ]);

        $collection = $collection->sortBy(fn($item, $key) => count($item['variants']));

        print_r($collection->values()->all());die;
}

/*
Result.


Array
(
    [0] => Array
        (
            [name] => Item 2
            [variants] => Array
                (
                    [0] => green
                )

        )

    [1] => Array
        (
            [name] => Item 1
            [variants] => Array
                (
                    [0] => blue
                    [1] => red
                )

        )

    [2] => Array
        (
            [name] => Item 3
            [variants] => Array
                (
                    [0] => orange
                    [1] => yellow
                    [2] => blue
                )

        )

)

*/

 

The sortBy method can also sort the collection with multiple attributes using array.

public function index()
{
        $collection = collect([
            ['name' => 'Item 1', 'price' => 89],
            ['name' => 'Item 2', 'price' => 107],
            ['name' => 'Item 3', 'price' => 37],
        ]);

        $collection = $collection->sortBy([
            ['name', 'asc'],
            ['price', 'desc']
        ]);

        print_r($collection->values()->all());die;
}

/*
result.

Array
(
    [0] => Array
        (
            [name] => Item 3
            [price] => 37
        )

    [1] => Array
        (
            [name] => Item 1
            [price] => 89
        )

    [2] => Array
        (
            [name] => Item 2
            [price] => 107
        )

)

*/

 

When using multiple attributes like the above example we can also implement closures and defined our sort operations.

public function index()
{
        $collection = collect([
            ['name' => 'Item 1', 'price' => 89],
            ['name' => 'Item 2', 'price' => 107],
            ['name' => 'Item 3', 'price' => 37],
        ]);

        $collection = $collection->sortBy([
            fn ($item, $key) => $item['name'] <=> $key['name'],
            fn ($item, $key) => $item['price'] <=> $key['price'],
        ]);

        print_r($collection->values()->all());die;
}

/*
Result.


Array
(
    [0] => Array
        (
            [name] => Item 1
            [price] => 89
        )

    [1] => Array
        (
            [name] => Item 2
            [price] => 107
        )

    [2] => Array
        (
            [name] => Item 3
            [price] => 37
        )

)

*/

 

 

Laravel Collection sortByDesc()

This method is the same as sortBy() above but the result is opposite order.

 

 

Laravel Collection sortDesc()

The sortDesc method is the opposite order for the sort method. Here is the example below:

public function index()
{
        $collection = collect([2, 4, 1, 5, 3]);
         
        $collection = $collection->sortDesc();

        print_r($collection->values()->all());die;
}

/*
Result.

Array
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)
*/

 

 

Laravel Collection sortKeys()

The sortKeys method will sort the collection using keys with an associative array.

public function index()
{
        $collection = collect([
            'id' => 123,
            'first' => 'John',
            'last' => 'Doe',
        ]);
         
        $collection = $collection->sortKeys();

        print_r($collection->all());die;
}

/*
Result.


Array
(
    [first] => John
    [id] => 123
    [last] => Doe
)
*/

 

Laravel Collection sortKeysDesc()

This method is the opposite order result for sortKeys method above.

 

Laravel Collection sortKeysUsing()

This method sortKeysUsing will sort the collection by keys with an associative array using the callback.

public function index()
{
        $collection = collect([
            'id' => 123,
            'first' => 'John',
            'last' => 'Doe',
        ]);
         
        $collection = $collection->sortKeysUsing('strnatcasecmp');

        print_r($collection->all());die;
}

/*

Result.

Array
(
    [first] => John
    [id] => 123
    [last] => Doe
)
*/

 

That's it you have basic knowledge on how to implement Laravel collection sort to your project. I hope it helps :)