How to define a case inside a Laravel query?

Laravel database query builder provides a convenient interface to create and run database queries. We can pass a database query in many ways, like defining a case inside a Laravel query. Consider the code snippet below.

$books = \DB::table("books")
    ->select("*",
        \DB::raw('(CASE 
            WHEN books.can_borrow = "0" THEN "Not Available" 
            WHEN books.can_borrow = "1" THEN "Available" 
            ELSE "Not Defined" 
            END) AS active_lable'))
    ->get();
dd($books);

The code snippet above explains how we can define a case inside a Laravel query, and set status accordingly.

The DB::raw() method is used to write a Case statement as a regular SQL expression. It checks for the book’s borrow status in each row and sets the book’s availability. So, if books.can_borrow is true, then the book is available, otherwise it is set as Not Available.

Executing the query with the get() method returns a collection of objects with all properties in this case. As select * is used for the example above.