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 ?
- How to Open URL in New Tab using Jquery?
- Laravel 7.x and 6.x Routing Tutorial
- Ng Bootstrap Modal in Angular 8 Example
- Bootstrap 4 Datepicker in Angular 9/8 Example
- Disable Registration Route in Laravel
- Bootstrap Timepicker in Angular Example
- Count Number of Pages in PDF - PHP Script
- Digital Signature PHP Script Example