How to use if condition in laravel select query?

How to use if condition in laravel select query?

In this post we will give you information about How to use if condition in laravel select query?. Hear we will give you detail about How to use if condition in laravel select query?And how to use it also give you demo for it if it is necessary.

We will learn how to use if condition in laravel select query. we can use mysql case when statement with db raw in laravel. If you want to use mysql function then you must have to use db raw function. in this example i will show you laravel select query with 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:

Also see:Import and Export CSV file in Laravel 5.8

$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….

Hope this code and post will helped you for implement How to use if condition in laravel select query?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

  +  26  =  36

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US