Home Laravel Laravel Collection SortBy and SortByDesc Method Example

Laravel Collection SortBy and SortByDesc Method Example

by Shahriar Sagor

Today now from this example,you will learn about how to use collection sort by method in laravel application. From here you can simply and also easy to use sort(),sortBy and SortByDesc() method in laravel application.

Laravel Collection object is provide us a several methods that also will help us to write our own logic. From here we will learn about how to use sort method of laravel applications.

Now in this example,i will give you a very simple and also easy array collection object then convert to sorting order collection. And other multidimensional array collection object then convert to asc and des order to array.Just need to follow bellow Example

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
    ]
]

Read Also : Laravel 8 Eloquent Global Scope Tutorial Example

I hope it will help you. Also you can follow us on Facebook

close

You may also like