In this tute, we will discuss case when in laravel query example. i would like to share with you if else condition in laravel 5. if you want to see example of if else condition laravel select query then you are a right place. This article will give you simple example of laravel select if condition.
In minor case we need to use if else condition in laravel 5 Eloquent. It might be use when you just need to send data to import or api etc.
I will give you example when you can use this kind of when case statement in mysql query. If you take "status" fields in users table with following meaning:
0 => User
1 => Admin
2 => SuperAdmin
So at this time we store 0 1 or 2 values in database table but when we select at that time it should become "User" "Admin" and "SuperAdmin".
We can write mysql query like this way:
SELECT '(CASE
WHEN users.status = "0" THEN "User"
WHEN users.status = "1" THEN "Admin"
ELSE "SuperAdmin"
END) AS status_lable'
FROM users
But you can write this query in Laravel like this way:
$users = User::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);
I hope it can help you....
Do you like below Tutorials ?
- CRUD Laravel 7.x and 6.x Example
- Image Upload Laravel 7.x and 6.x Tutorial
- Laravel 7.x and 6.x Delete File from public folder example
- How to delete directory in Laravel 7.x and 6.x?
- How to create directory if not exists in Laravel 7.x and 6.x?
- Laravel 7.x and 6.x get all files in directory example
- Laravel 7.x and 6.x check file exists in folder example
- Ajax Autocomplete Textbox in Laravel 7.x and 6.x Example