Sling Academy
Home/PHP/Laravel Query Builder: Using ‘ORDER BY’ Clause

Laravel Query Builder: Using ‘ORDER BY’ Clause

Last updated: January 17, 2024

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.

Next Article: Executing Subqueries in Laravel Query Builder: Tutorial & Examples

Previous Article: Laravel Query Builder: Using ‘AND’ and ‘OR’ Operators

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array