Get your next remote job on LaraJobs.
1 contributor Edit on GitHub Laravel

Sort your Laravel Eloquent queries results using orderBy()

Table of contents:

Sort your Laravel Eloquent queries results using orderBy()

The basics of orderBy()

Before we dive deep, let’s understand the foundation:

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

In this snippet, we’re using Laravel Eloquent to fetch users from their table and ordering them in descending order by their names.

Parameters:

  • The column’s name.
  • The order direction: Either asc (the default value) for ascending or desc for descending.

Multi-column sorting using orderBy()

What if you want to sort by multiple columns? Simple. Just chain multiple orderBy() methods:

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

This way, Eloquent sorts users by their names first. If two or more users have the same name, it then sorts those users by their email in ascending order.

I actually learned that after years of SQL and Laravel experience. 😅

Getting fancy with orderByRaw()

When you need a more complex sorting mechanism, Laravel’s got you covered with orderByRaw():

$orders = User::query()
->orderByRaw('updated_at - created_at DESC')
->get();

This advanced method lets you sort the results based on the difference between the updated_at and created_at timestamps. Handy, right?

Use reorder() to unorder what’s been ordered

If you need to undo the ordering of a query you are building based on some condition, you can use the reorder() method:

$ordered = User::orderBy('name');
 
$unordered = $ordered->reorder()->get();

And if you wish to reset and apply a completely new ordering without calling orderBy() again:

$ordered = User::query()->orderBy('name');
 
$reorderedByEmail = $query->reorder('email', 'desc')->get();

I’ll never get bored of Laravel’s convenience!

Benjamin Crozat

Written by Benjamin Crozat

Indie hacker, blogger, and AI enthusiast building things with the TALL stack. 🔥

Follow me on:

Recommended articles

20+ Laravel best practices, tips and tricks to use in 2023 20+ Laravel best practices, tips and tricks to use in 2023

Learning a framework can be overwhelming, but time and execution will make you a master. Here are some best practices to help you toward your goal.

Modified on Oct 17, 2023

Learn how to sort any kind of array in PHP Learn how to sort any kind of array in PHP

Let me walk you through some of the most useful functions in PHP that will enable you to sort any kind of array.

Published on Nov 9, 2023

PHP
Unlock the power of Laravel's query builder where clauses Unlock the power of Laravel's query builder where clauses

Unleash Laravel's query builder with my deep dive into the power of "where" clauses—triggering conditions, exclusions, JSON queries, and more.

Published on Sep 12, 2023

9 testing best practices for Laravel in 2023 9 testing best practices for Laravel in 2023

Are you familiar with testing? Good. Here are a bunch of best practices to help you level up even more!

Modified on Oct 27, 2023

7 Laravel RESTful APIs best practices for 2023 7 Laravel RESTful APIs best practices for 2023

Master the art of crafting RESTful APIs with Laravel thanks to these best practices.

Modified on Oct 10, 2023

Gold sponsors New

  • Wire Elements
    Beautiful handcrafted Livewire components.
    Check site
Your business here

Partners

If you buy from one of my partners below, I will be compensated at no cost to you. These are services I use or used, and 100% stand behind.

  • Scalable and reliable VPS hosting.
    Bonus: $200 of free credits
    Check site
  • The Google Analytics alternative without compromise.
    Free trial: 30 days
    Bonus: $10 off your first invoice
    Check site
  • Flare
    Track PHP and JavaScript errors in one place.
    Free trial: 10 days
    Check site
  • Keep track of your Google rankings.
    Free trial: 7 days
    Promo code: WELCOME30
    Check site
- / -