Why and How to Use “CASE WHEN” Statement in Laravel Eloquent?

In Laravel Eloquent, you can use the Case statement in a query to create conditional statements in your SQL query. You can use the when method in combination with the Case statement to add conditions to your query. Here’s an example:

$users = DB::table('users')
                ->select(DB::raw('CASE
                            WHEN status = 1 THEN "Active"
                            ELSE "Inactive"
                        END AS status_name'), 'name')
                ->get();

In this example, the when method is used to create a conditional statement that checks the value of the status column. If the value is 1, the status_name column will be set to “Active”, and if the value is anything else, the status_name column will be set to “Inactive”.
You can use a raw query in Laravel to include a CASE WHEN statement in your query, without using a model class. Here’s an example:

$users = DB::select(DB::raw("SELECT name, 
                                    (CASE 
                                        WHEN status = 1 THEN 'Active' 
                                        ELSE 'Inactive' 
                                    END) AS status_name 
                            FROM users"));

In this example, the DB::select method is used to execute a raw SQL query, which includes a CASE WHEN statement. The DB::raw method is used to include the raw SQL in the query. The query returns the name and the status of each user, with the status being either “Active” or “Inactive” depending on the value of the status column.
You can use the Case statement in Laravel’s query builder to add conditional logic to your queries, even when using a model class. Here’s an example:

$users = User::select(DB::raw("name, 
                                (CASE 
                                    WHEN status = 1 THEN 'Active' 
                                    ELSE 'Inactive' 
                                END) AS status_name"))
            ->get();

In this example, the User model class is used to retrieve data from the users table. The select method is used to specify the columns that should be returned, and the DB::raw method is used to include a CASE WHEN statement in the query. The query returns the name and the status of each user, with the status being either “Active” or “Inactive” depending on the value of the status column.