Laravel Query Builder: Using ‘ORDER BY’ Clause

Updated: January 17, 2024 By: Guest Contributor Post a comment

Introduction

Laravel’s Eloquent ORM is a powerhouse for database operations, providing an expressive and fluent interface that allows web artisans to work with databases in a very convenient manner. One of the core features of Laravel’s Query Builder is the ORDER BY clause, which enables you to sort your result sets by one or more columns. In this tutorial, we will delve into how to utilize the ORDER BY clause effectively in Laravel.

Understanding the ORDER BY Clause

The ORDER BY clause is used to sort the result set from a SELECT statement by one or more columns, either in ascending or descending order. By default, if no order direction is specified, it will sort in ascending order (ASC). To specify descending order, you can use the keyword DESC.

$users = DB::table('users')
 ->orderBy('name', 'asc')
 ->get();

Basic Usage

Let’s begin with a basic example. Suppose you have a users table and you wish to retrieve all users sorted by their name in ascending order:

$users = DB::table('users')
 ->orderBy('name')
 ->get();

If you want to sort them in descending order, you simply add the second parameter ‘desc’ to the orderBy method:

$users = DB::table('users')
 ->orderBy('name', 'desc')
 ->get();

It is important to note that when using Eloquent models, the syntax remains the same:

$users = User::orderBy('name', 'desc')
 ->get();

Of course, it is not just strings you can order by; ordering by numerical values, dates, and other data types is also possible.

Ordering by Multiple Columns

You can also sort by multiple columns. For instance, you might want to sort users by their type and then by name within each type:

$users = DB::table('users')
 ->orderBy('type')
 ->orderBy('name')
 ->get();

With Eloquent, the same logic applies:

$users = User::orderBy('type')
 ->orderBy('name')
 ->get();

Using orderByRaw

In some cases, you may need more complex ordering logic that can’t be easily achieved with the orderBy method. This is where orderByRaw comes in handy. With orderByRaw, you can write a raw order by query:

$users = DB::table('users')
 ->orderByRaw('IF(status = "active", 1, 0) desc, name asc')
 ->get();

Above, the users will be sorted primarily by their status being ‘active’ and then alphabetically by their name.

Dynamic Ordering with when

There may be situations where you need to apply different orderings based on certain criteria or user input. Laravel’s query builder provides the when method, which enables you to conditionally apply query clauses:

$sortBy = request()->query('sort_by', 'name');
$sortOrder = request()->query('sort_order', 'asc');

$users = DB::table('users')
 ->when($sortBy, function ($query, $sortBy) use ($sortOrder) {
 $query->orderBy($sortBy, $sortOrder);
 })
 ->get();

This way, your application can dynamically order results based on URL query parameters or other conditions.

Conclusion

In conclusion, the ORDER BY clause is a versatile and powerful feature of Laravel’s Query Builder. Throughout this guide, we explored several scenarios that illustrated the flexibility of orderBy, from basic alphabetical sorting to more complex conditions using orderByRaw and conditional logic with when. By understanding how to leverage ORDER BY in Laravel, you can build more intuitive and efficient database queries that cater to your application’s needs.

As Laravel continues to grow and evolve, it brings even more tools and syntactic sugar to make database interactions a breeze for developers. Remember to always refer to the official Laravel documentation to stay updated with the most current best practices and new features.