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"
END) AS status_lable'))
It is a very simple, you can use this way.
I hope you found your best...
Do you like below Tutorials ?
- Laravel 5.5 validation example with custom message
- Laravel 5.5 create zip archive file and download example
- Laravel 5.5 Jquery Ajax Request Example From Scratch
- Laravel 5.5 pagination example from scratch
- Ajax CRUD example in Laravel 5.5 application
- Class Form not found in Laravel 5.5
- Laravel 7.x and 6.x get last query log example
- Laravel 5.5 Image Upload example