In this laravel tutorial, you will learn how to use order by with eloquent queries in laravel.
As well as, how to use laravel order by with relation, date desc, desc limit, asc, all(), random, created_at, raw etc. And multiple order by in one query.
Sometime, you may want to fetch data from the database in a particular order. This tutorial will provide you multiple example of laravel order by.
Laravel OrderBy Example
In this tutorial, you will learn the following laravel orderBy with queries:
- Laravel OrderBy
- Laravel OrderBy Multiple
- Laravel Order By Date Desc
- Laravel Orderby Belongs to Relationship
- Laravel Orderby with Limit
1: Laravel OrderBy
Basic uses of laravel orderBy as follow:
// order by desceding
$users = User::orderBy('name', 'desc')->get();
//SELECT * FROM `users` ORDER BY `name` DESC
// order by ascending
$users = User::orderBy('name', 'asc')->get();
//SELECT * FROM `users` ORDER BY `name` ASC
2: Laravel OrderBy Multiple
Multiple orderBy with eloquent query as follow:
User::orderBy('name', 'DESC')
->orderBy('email', 'ASC')
->get();
This query will Produce the following sql query:
SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC
3: Laravel Order By Date Desc
Laravel date orderBy query as follow:
User::orderBy('created_at', 'DESC')->get();
This query will Produce the following sql query:
SELECT * FROM `users` ORDER BY `created_at` DESC
4: Laravel Orderby Belongs to Relationship
Laravel orderBy with relationship query as follows:
// order by asceding
$posts = Post::with(['author' => function ($q){
$q->orderBy('name');
}])
->get();
// for desceding order
$posts = Post::with(['author' => function ($q){
$q->orderBy('name', 'DESC');
}])
->get();
5: Laravel Orderby with Limit
Laravel orderBy with limit as follows:
// order by desceding
$users = User::Orderby('id', 'desc')->limit(5)->get();
// for asceding order
$users = User::Orderby('id', 'asc')->limit(5)->get();
Conclusion
In this laravel tutorial, you have learned laravel orderBy with eloquent queries.
Recommended Laravel Tutorials