Hello Friends 👋,
Welcome To Infinitbility! ❤️
This article will help you to write order by cases query like when we use Order by case when query in sql then how we use or implement In laravel.
Let’s start today’s article Laravel order by case when example
The Laravel provide orderByRaw function to implement case when query and we are going to use.
First we have to understand why we need case when in query.
Assume you have multiple key in single column example you have gender column and you are storing
You want to show data of first male user than female and after that others users, then you have to use case when query where you can define which user you want show first, second, and last.
Let’s understand with example.
1$users = DB::table("users")->orderByRaw("CASE WHEN gender = 'Male' then 1 WHEN gender = 'Female' then 2 WHEN gender = 'Others' then 3 Else 4 END DESC")->get();
Thanks for reading…
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.