How to use if condition in laravel select query?

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Hello dev’s
Here we will learn about how to use if condition in laravel select query. We can use mysql case when statement with db raw query in laravel. So if you want to use mysql function then you must have to use db raw function. In this example i will show you how to use laravel select query with if condition.

In minor case you must need to use if else condition in laravel 5, laravel 6, laravel 7 and laravel 8 Eloquent query. It need must be use when we just need to send data to import or send api etc.

I will give you a short example when you can use this kind of when case statement in mysql query. If we take “usertype” fields in our users table with following meaning:

0 => User

1 => Admin

2 => SuperAdmin

So at this time we store only 0 1 or 2 values in database table. But when we need to select at that time it should become “User” “Admin” or “SuperAdmin”.

That time 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

Read Also : MYSQL Query for Data between Two Dates Example

But when we need to write this query in Laravel,that time it will be 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);

Thanks for read, i hope it will help you……… Also you can follow us on Facebook.

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →