Hello there Geeks, We’ll look at how to use the if condition in a Laravel select query. When using a statement with a raw database in Laravel, we can use the mysql case. If you want to use the mysql function, you must use the db raw function. In this example, I’ll show you how to create a Laravel select query with an if condition.
In minor cases, if else conditions must be used in Laravel 5, Laravel 6, Laravel 7, Laravel 8, and Laravel 9 Eloquent. It could be useful when you only need to send data to an import or an API, for example.
I’ll show you an example of how to use this type of when case statement in a MySQL query. If you take the “status” fields in the users table and interpret them as follows:
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
However, in Laravel, you can write this query as follows:
$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);
All the best nerd!