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.
SELECT Query:
$users = \DB::table("users")
->select("*",
\DB::raw('(CASE
WHEN users.status = "0" THEN "User"
WHEN users.status = "1" THEN "Admin"
ELSE "SuperAdmin"
END) AS status_lable'))
->get();
dd($users);
It is a very simple, you can use this way.
I hope you found your best...
Do you like below Tutorials ?
- PHP Convert Date String to Datetime Object
- Laravel Validation Different Value Example
- Jquery Redirect to URL After Specific Time Example
- User Roles and Permissions in Laravel Example
- How to Get Value of Selected Option in Vue JS?
- Laravel Change Password OLD Password Validation Example
- Vue JS Get String Length Example
- How to Active and Inactive Status in Laravel?