PHP Laravel Collection Sort By Multiple Fields

Today, We want to share with you PHP Laravel Collection Sort By Multiple Fields.In this post we will show you laravel collection order by array, hear for laravel collection->sort by value we will give you demo and example for implement.In this post, we will learn about Laravel Collection Macros: Adding a “sortByMuti” function with an example.

PHP Laravel Collection Sort By Multiple Fields

There are the Following The simple About Using OrderBy for multiple columns in Laravel 5/6/7 Full Information With Example and source code.

As I will cover this Post with live Working example to develop laravel collection sort by nested key, so the some major files and Directory structures for this example is following below.

Read Also:  Laravel Eloquent Collection Sort By Relation column

Laravel is a web application framework with expressive, elegant syntax.The PHP Framework for Web Artisans,freeing you to create without sweating the small things. CRUD Operation With Server Side.

Laravel Collection Sort By Two Fields

The Keys are the Key in Laravel Multiple Field sortBy() : PHP

public function index()
{
    $collection = collect([
            ['id' => 1, 'name' => 'Hanuman', 'city' => 'Mahshana'],
            ['id' => 2, 'name' => 'abhishek', 'city' => 'Rajesthan'],
            ['id' => 3, 'name' => 'Bharat', 'city' => 'Rajesthan'],
            ['id' => 4, 'name' => 'abhishek', 'city' => 'Mahshana'],
        ]);
  
    $sorted = $collection->sortBy(function ($product, $key) {
                        return $product['city'].$product['name'];
                    });
  
    $sorted->all();
  
    dd($sorted);
}

Output:
Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [3] => Array
                (
                    [id] => 4
                    [name] => abhishek
                    [city] => Mahshana
                )
            [0] => Array
                (
                    [id] => 1
                    [name] => Hanuman
                    [city] => Mahshana
                )
            [1] => Array
                (
                    [id] => 2
                    [name] => abhishek
                    [city] => Rajesthan
                )
            [2] => Array
                (
                    [id] => 3
                    [name] => Bharat
                    [city] => Rajesthan
                )
        )
)

Web Programming Tutorials Example with Demo

Read :

Read Also:  PHP Laravel 6 Multiple Database Connections Tutorial

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about laravel query builder order by two columns.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.