Order By Query In Laravel 9 Example

In this article, we will see order by query in the laravel 9 examples. Here, we will learn how to use order by in laravel 9. Also, we will give you an example of laravel 9 order by with where clause and query of order by in MySQL. You can also write multiple order by in a single laravel query.

So, let's see laravel 9 order by query example, multiple order by query in laravel 9, laravel 9 order by with where condition, and laravel 9 order by desc example.

The orderBy method allows you to sort the results of the query by a given column. The first argument accepted by the orderBy method should be the column you wish to sort by, while the second argument determines the direction of the sort and may be either asc or desc.

  1. SQL Query of Order By
  2. Laravel 9 orderBy
  3. Laravel 9 orderBy Multiple
  4. Laravel 9 orderBy Date Desc
  5. Laravel 9 orderBy with Relationship
  6. Laravel 9 orderBy with Limit

In MySQL query, the ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

SQL Query:

MySQL Order By Syntax.

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

Example:

SELECT * FROM users
ORDER BY id;

 

 

Laravel 9 orderBy Query:

In laravel 9, you can use the orderBy method for ordering records.

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

 

Laravel 9 orderBy Multiple:

Now, we will see multiple orderBy in a single query.

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

 

Laravel 9 orderBy Date Desc:

In this example, we will see the date orderBy query example.

User::orderBy('created_at', 'DESC')->get();

User::orderBy('updated_at', 'ASC')->get();

 

Laravel 9 orderBy with Relationship:

 In this example, the Post model belongs to the User model, and you want to get posts data order by updated_at

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

 

 

Laravel 9 orderBy with Limit:

The limit methods limit the number of results returned from the query.

$users = User::orderBy('id', 'desc')->limit(10)->get(); 
 
$users = User::orderBy('id', 'asc')->limit(10)->get();

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS