Friday, August 29, 2025
HomeLanguageslaravel Order By Example

laravel Order By Example

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

Recommended:-Laravel Try Catch

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32249 POSTS0 COMMENTS
Milvus
80 POSTS0 COMMENTS
Nango Kala
6615 POSTS0 COMMENTS
Nicole Veronica
11789 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11837 POSTS0 COMMENTS
Shaida Kate Naidoo
6731 POSTS0 COMMENTS
Ted Musemwa
7011 POSTS0 COMMENTS
Thapelo Manthata
6687 POSTS0 COMMENTS
Umr Jansen
6699 POSTS0 COMMENTS