Eloquent Order By Query Example in Laravel

Sovary September 27, 2022 528
2 minutes read

Hello friends, in this article we will explain how to use order by query in Laravel. orderBy is the method that allow you to sort the records of given columns name. There are two arguments in the method orderBy first argument is the column name which you want to sort by, but the sort direction there are two direction to sort in ascending or descending, so the second argements determines whether asc or desc.

We will show you example with query clause of order by in raw SQL statment and multiple order by in Laravel method. The key in this section are asc which to sorted in ascending and desc for sort descending value with orderBy method. So, let's see how to use order by in laravel 6, laravel 7, and laravel 8 order by with where clause.

SQL STATEMENT

-- Sort in ascending

SELECT column1, column2
FROM table_name
ORDER BY column1, column2 ASC;

-- Sort in descending

SELECT column1, column2
FROM table_name
ORDER BY column1, column2 DESC;

Laravel orderBy Query

This is example how we use the orderBy() method to retrieve data users and sorted by descending. 

$users = DB::table('users')
         ->orderBy('name', 'desc')
         ->get();

Laravel orderBy Date Query

In this example, we will see the date orderBy() desceding and ascending query as below example.

// Retrieved user in descending
User::orderBy('created_at', 'DESC')->get();

// Retrieved user in ascending
User::orderBy('updated_at', 'ASC')->get();

Laravel orderBy Multiple Columns Query

See below example how to sorted orderBy() with multiple columns

User::orderBy('name', 'DESC')
    ->orderBy('email', 'ASC')
    ->get();

Laravel orderBy with Relationship

For example, in case we have model relationship with other model like Comment model belongs to Post and we want to get comments data which order by updated_at.

$comments = Post::with(['comments' => function ($query) 
{
    $query->orderBy('updated_at', 'asc');
}])->get();

Laravel orderBy with Limit

Example of using limit method to limit the results returned from the query.

$posts = Post::orderBy('title', 'desc')->limit(10)->get(); 
 
$posts = Post::orderBy('title', 'asc')->limit(10)->get();

Thanks for reading the article. Please stay tune with subscribe newsletter.

You might also like..

 

Laravel  PHP  Laravel 9  Query Builder 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him