ItSolutionStuff.com

How to Use If Condition in Laravel Select Query?

By Hardik Savani • April 16, 2024
Laravel MySql

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, laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 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....

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Use DB Raw Query in Laravel?

Read Now →

Laravel Sum Query with Where Condition Example

Read Now →

Laravel Case Sensitive Query Search Example

Read Now →

How to Get Last Executed Query in Laravel 8?

Read Now →

PHP Laravel Inner Join Query Example

Read Now →

Laravel Eloquent selectRaw() Query Example

Read Now →

How to use Union Query with Laravel Eloquent?

Read Now →

Laravel One to Many Eloquent Relationship Tutorial

Read Now →

Laravel Many to Many Eloquent Relationship Tutorial

Read Now →

How to Get Last Record from Database in Laravel?

Read Now →

How to Concat Two Columns in Laravel?

Read Now →

How to Get Last Executed Query in Laravel?

Read Now →

How to Get Query Log in Laravel Eloquent?

Read Now →