Home / Snippets / How to Order Laravel Eloquent Records
How to Order Laravel Eloquent Records cover

How to Order Laravel Eloquent Records

1.9K

2 years ago

0 comments

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");
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this