Table of contents

Laravel Eloquent Order By

In this post, you will learn how to implement Laravel Eloquent Order By method to your query. The orderBy() method will able us to sort the record. We will tackle several examples so that easier for you to follow and implement in your project.

 

Laravel has a powerful eloquent query that able us to shorten our query with helpful methods we can use. One of them is the orderBy() method that able us to order the record upon querying before we see the result from the database.

 

Now let's start our Laravel eloquent orderBy method.

 

Laravel Eloquent orderBy() Example

In this example, we can able to sort by ascending the ads record using the title field.

public function index()
{
    $ads = Ads::where('status', 'published')
        ->orderBy('title')
        ->get();

    print_r($ads);die;
}

 

Laravel Eloquent orderBy() with DESC

In this example, we sort by descending the ads records using the title field.

public function index()
{
    $ads = Ads::where('status', 'published')
        ->orderBy('title', 'desc')
        ->get();

    print_r($ads);die;
}

 

Laravel Eloquent orderByDesc() Example

In this section, we use the orderByDesc() method to sort by descending the record.

public function index()
{
    $ads = Ads::where('status', 'published')
        ->orderByDesc('title')
        ->get();

    print_r($ads);die;
}

 

 

Laravel Eloquent orderByRaw() Example

In this example, we use the orderByRaw to sort the record with multiple fields. In default, the orderByRaw() is sorted by ascending.

public function index()
{
    $users = User::where('status', 'published')
        ->orderByRaw("concat(first_name, ' ', last_name)")
        ->get();

    print_r($users);die;
}

 

 

Laravel Eloquent orderByRaw() with DESC

To sort the orderByRaw() by descending we will just add DESC.

public function index()
{
    $users = User::where('status', 'published')
        ->orderByRaw("concat(first_name, ' ', last_name) DESC")
        ->get();

    print_r($users);die;
}

 

That's it about Laravel's eloquent sorting I hope it helps.

 

Cheers :)