Sort your Laravel Eloquent queries results using orderBy()

Sort your Laravel Eloquent queries results using orderBy()

Modified
Dec 20, 2023
Written by
Benjamin Crozat
0
comments
2 minutes
read

The basics of orderBy()

Before we dive deep, let’s understand the foundation of the orderBy() method:

$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 thanks to the orderBy() method.

Its parameters are:

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

The orderByDesc() method

If you want to sort your results in descending order, you can also use the orderByDesc() method, which is a shortcut for orderBy('column', 'desc'):

$users = User::query()
    ->orderBy('name', 'desc') // [tl! --]
    ->orderByDesc('name') // [tl! ++]
    ->get();

It’s all in the details! 👌

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 only 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 already 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!

About Benjamin Crozat
Benjamin Crozat

Hi! I’m from the South of France and I’ve been a self-taught web developer since 2006. When I started learning PHP and JavaScript, PHP 4 was still widely used, Internet Explorer 6 ruled the world, and we used DHTML to add falling snow on websites.

Being able to educate myself for free on the web changed my life for the better. Giving back to the community was a natural direction in my career and I truly enjoy it.

Therefore, I decided to take action:

  1. I launched this blog in September 2022 with the goal to be in everyone’s Google search. I get more than tens of thousands of monthly clicks from it and even more visits overall (my analytics dashboard is public by the way).
  2. I also started growing my X (formerly Twitter) account at the same time, which has now over 7,000 followers.
  3. All the content I write is free thanks to my sponsors.

I also want to be completely free with my time and make a living with my own products. In April 2024, I launched Nobinge, a tool to summarize and chat with your content, including YouTube videos.

Believe me, I’m just getting started!

0 comments

You need to be signed in to comment this post.
Sign in with GitHub