Order by using multiple columns and manually array field in Laravel?
In this post we will give you information about Order by using multiple columns and manually array field in Laravel?. Hear we will give you detail about Order by using multiple columns and manually array field in Laravel?And how to use it also give you demo for it if it is necessary.
If you want to sort multiple columns in Laravel by using orderBy(). Whenever you need to give multiple column in your query then you can use twice time orderBy() and give them. you can give multiple columns in laravel by following example :
Users Table :
id | site_id | sub_site_id | name | |
---|---|---|---|---|
1 | 4 | 7 | john | john@gmail.com |
2 | 3 | 4 | ram | ram@gmail.com |
3 | 4 | 2 | ader | ader@gmail.com |
4 | 3 | 1 | jay | jay@gmail.com |
5 | 4 | 1 | yamee | yamee@gmail.com |
Multiple Columns OrderBy
$data = DB::table('users')
->select('users.*')
->orderBy('site_id', 'asc')
->orderBy('sub_site_id', 'asc')
->get();
Result :
id | site_id | sub_site_id | name | |
---|---|---|---|---|
4 | 3 | 1 | jay | jay@gmail.com |
2 | 3 | 4 | ram | ram@gmail.com |
5 | 4 | 1 | yamee | yamee@gmail.com |
3 | 4 | 2 | ader | ader@gmail.com |
1 | 4 | 7 | john | john@gmail.com |
you can also give array in order by method, Laravel give facility to sort manual array in order by, following example through specific array in order by.
Result :
id | site_id | sub_site_id | name | |
---|---|---|---|---|
3 | 4 | 2 | ader | ader@gmail.com |
1 | 4 | 7 | john | john@gmail.com |
4 | 3 | 1 | jay | jay@gmail.com |
5 | 4 | 1 | yamee | yamee@gmail.com |
2 | 3 | 4 | ram | ram@gmail.com |
we are using string in order by like pending, approved and rejected status then following example are useful.
$data = DB::table('users')
->select('users.*')
->orderByRaw(DB::raw("FIELD(status, 'Pending', 'Approved', 'Rejected')"))
->get();
if you want to give ‘ASC’ or ‘DESC’ order in query then following example :
$data = DB::table('users')
->select('users.*')
->orderByRaw(DB::raw("FIELD(sub_site_id, 2, 7, 1, 4) DESC"))
->get();
Try this….
Hope this code and post will helped you for implement Order by using multiple columns and manually array field in Laravel?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs