Order by using multiple columns field in Laravel?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this tutorial i will show you how to using multiple columns order by in laravel. Now here If we want to sort a multiple columns in Laravel by using orderBy(). Or Whenever we need to give multiple column in our query then we can use twice time orderBy() and then give them. So we 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

Now we can also give an array in order by method, in Laravel give facility to sort manual array in order by, 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

So we can using string in order by as like pending, approved and rejected status then the following example are useful.

$data = DB::table('users')
    ->select('users.*')
    ->orderByRaw(DB::raw("FIELD(status, 'Pending', 'Approved', 'Rejected')"))
    ->get();

So if we want to give a ‘ASC’ or ‘DESC’ order in query then we can following this example :

$data = DB::table('users')
    ->select('users.*')
    ->orderByRaw(DB::raw("FIELD(sub_site_id, 2, 7, 1, 4) DESC"))
    ->get();

Read Also : How to count number of files in folder and remove all files in folder in laravel example?

Thanks for read this, I hope it will you. You can also follow us on Facebook.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →