Laravel 9 - All About Sorting Collection

Published on Jul 29, 2022

Hello Artisans, today I'll show you how to sort collections using Laravel predefined collection methods. Sometimes we need to sort the collection after retrieving the result from our database. Laravel gives us some useful methods to sort the results without any hassle. So, no more talk, let's see some useful methods to sort the results.

Note: Tested on Laravel 9.19.

Sort By Name

We'll see here how we can sort our result by any of the field which we've in our result. Like we've a column called name in our database and we want to sort our result by name. Then we can use the sortBy() method to achieve our expected result.

public function sortByName()
    {
        $collection = collect([
            ['id' => 1, 'name' => 'John', 'email' => '[email protected]'],
            ['id' => 2, 'name' => 'Sam', 'email' => '[email protected]'],
            ['id' => 3, 'name' => 'Bilal', 'email' => '[email protected]'],
            ['id' => 4, 'name' => 'Lisa', 'email' => '[email protected]'],
            ['id' => 5, 'name' => 'Samuel', 'email' => '[email protected]']
        ]);

        dd($collection->sortBy('name'));
    }

here we can also use email or id to sort the results.

Sort By Two Fields

We'll see here how we can sort our result by two of the field which we've in our result. Like we've a column called name and email in our database and we want to sort our result by these two fields. Then we can also use the sortBy() method to achieve our expected result but we need to do some extra workaround.

 public function sortByTwoField()
    {
        $collection = collect([
            ['id' => 1, 'name' => 'John', 'email' => '[email protected]'],
            ['id' => 2, 'name' => 'Sam', 'email' => '[email protected]'],
            ['id' => 3, 'name' => 'Bilal', 'email' => '[email protected]'],
            ['id' => 4, 'name' => 'Lisa', 'email' => '[email protected]'],
            ['id' => 5, 'name' => 'Samuel', 'email' => '[email protected]']
        ]);

        $filterd = $collection->sortBy(function ($data, $key) {
            return $data['name'].$data['email'];
        });

        dd($filterd);
    }

Sort By Date

We'll see here how we can sort our result by date. Like we've a column called date in our database and we want to sort our result by these field. Then we can also use the sortBy() method to achieve our expected result. See the below code snippet.

public function sortByDate()
    {
        $collection = collect([
            ['id' => 1, 'name' => 'John', 'created_at' => '2022-09-13 00:05:06'],
            ['id' => 2, 'name' => 'Sam', 'created_at' => '2022-07-13 00:05:06'],
            ['id' => 3, 'name' => 'Bilal', 'created_at' => '2022-05-13 00:05:06'],
            ['id' => 4, 'name' => 'Lisa', 'created_at' => '2022-02-13 00:05:06'],
            ['id' => 5, 'name' => 'Samuel', 'created_at' => '2022-01-13 00:05:06']
        ]);

        $filterd = $collection->sortBy(function ($data, $key) {
            return $data['created_at'];
        });

        dd($filterd);
    }

Sort By Count

We'll see here how we can sort our result by count. Like we've a column called articles in our database and we want to sort our result by these field. Then we can also use the sortBy() method to achieve our expected result. See the below code snippet.

public function sortByCount()
    {
        $collection = collect([
            ['id' => 1, 'name' => 'John', 'articles' => ['Laravel','Jquery']],
            ['id' => 2, 'name' => 'Sam', 'articles' => ['python','django','flask']],
            ['id' => 3, 'name' => 'Bilal', 'articles' => ['Linux security']],
            ['id' => 4, 'name' => 'Lisa', 'articles' => []],
        ]);

        $filterd = $collection->sortBy(function ($data) {
            return $data['articles'];
        });

        dd($filterd);
    }

Sort By Relationship

We'll see here how we can sort our result by relationship. Like we've a table called articles in our database and we want to sort our result by category name. Then we can also use the sortBy() method to achieve our expected result. See the below code snippet.

public function sortByRelationship()
    {
        $student = App\Article::get()->sortBy(function($query){
            return $query->category->name;
        })
            ->all();
        dd($student);

    }

That's about our today's tutorial. You can find all of the available methods https://laravel.com/docs/9.x/collections#available-methods.

That's it for today. Hope you've enjoyed this tutorial. Thanks for reading. 🙂

Comments (0)