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.
$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…