Posts Learn Components new Snippets new Categories Tags About
/

How to Order Laravel Eloquent Records

Learn how to order Laravel Eloquent records the easy way and get your data sorted in an "ascending" or "descending" order

Created on Oct 14, 2021

29 views

In this short snippet, you will learn how to order your Laravel Eloquent records in an "ascending" or "descending" order so let's get started.

Laravel Order By One Column


To order by using one column you can call the "orderBy()" method and passing in the "column" to order. By default, this will order it in an "Ascending" order. Do refer the code below for this example.
<?php

Post::query()
    ->orderBy('published_at')
    ->get();
To set the order by descending you can write your code like the following.
<?php

Post::query()
    ->orderBy('published_at', 'desc')
    ->get();

// For an alternative you can make use the "orderByDesc" method.
Post::query()
    ->orderByDesc('published_at', 'desc')
    ->get();

Laravel Order By Two Column


To order by two columns or more you can just chain the method like below.
<?php

Post::query()
    ->orderBy('published_at', 'desc') // DESC
    ->orderBy('user_id') // ASC
    ->get();

// For an alternative you can make use the "orderByDesc" method.
Post::query()
    ->orderByDesc('published_at', 'desc') // DESC
    ->orderBy('user_id') // ASC
    ->get();

Order By The Eloquent Collection


If you already get the eloquent collection such as by using "all()" and then chaining it with the "sortBy()" method. Do note that this sorting is less efficient than calling the "orderBy" method available to the Query Builder.
<?php

// Sort post in ascending order of title
$results = Posts::query()
    ->all()
    ->sortBy("title");

// Sort post in descending order of title
$results = Posts::query()
    ->all()
    ->sortByDesc("title");
new

If you like our tutorial, do make sure to support us with some coffee. We need the juice to write the content during the night 🤙🏻