Laravel Eloquent - When Case Statement in Select Query Example

August 14, 2018 | Category : Laravel 5.6 Laravel 5.5 Laravel 5 Laravel PHP

In this article, you will learn how to use if else condition in laravel select query using db raw. We require many times to add if condition in laravel eloquent query using when case statement. So, In mysql, if you want to add else if condition then mysql provided when case statement. we can use it same way as we use if else.

Actually, I was read laravel documentation and i was trying to run some query and testing how we can use it. Same time i have idea to how we can add if else condition in select statement for status field like if 0 means 'User', 1 means 'Admin' and 2 means 'SuperAdmin'. I know mysql provide when case statement and i also know we can use mysql function using DB::raw. i want to share this small peas of example so new developer can see how we can use it.

Just check bellow example and you will got it how we can use it.


$users = \DB::table("users")



WHEN users.status = "0" THEN "User"

WHEN users.status = "1" THEN "Admin"

ELSE "SuperAdmin"

END) AS status_lable'))



It is a very simple, you can use this way.

I hope you found your best...