Order by using multiple columns and manually array field in Laravel?

By Hardik Savani | January 25, 2016 | | 87011 Viewer | Category : Laravel


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 :

idsite_idsub_site_idnameemail
147johnjohn@gmail.com
234ramram@gmail.com
342aderader@gmail.com
431jayjay@gmail.com
541yameeyamee@gmail.com

Multiple Columns OrderBy

$data = DB::table('users')

->select('users.*')

->orderBy('site_id', 'asc')

->orderBy('sub_site_id', 'asc')

->get();

Result :

idsite_idsub_site_idnameemail
431jayjay@gmail.com
234ramram@gmail.com
541yameeyamee@gmail.com
342aderader@gmail.com
147johnjohn@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 :

idsite_idsub_site_idnameemail
342aderader@gmail.com
147johnjohn@gmail.com
431jayjay@gmail.com
541yameeyamee@gmail.com
234ramram@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....



Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: