Eloquent Order By Query Example in Laravel

Sovary September 27, 2022 574
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

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him