Search code examples
sqllaravellumencase-when

Raw query CASE WHEN is not working in Lumen?


I want to use CASE WHEN in Lumen, but it returns the message "Oops! An Error Occurred. The server returned a 500 Internal Server Error."

//Working
$result = DB::table('Users')
    ->select(DB::raw('count(*) as user_count'))
    ->where('user_id', 'A1')        
    ->get(); 
// Working
$result = DB::select('SELECT CASE WHEN user_status="new" THEN "New"  ELSE "Expired" END AS new_status FROM Users WHERE user_id="A1"');

//Failed
$result = DB::table('Users')
    ->select(DB::raw('CASE WHEN user_status="new" THEN "New"  ELSE "Expired" END AS new_status'))
    ->where('user_id', 'A1')        
    ->get();

Why did it fail?

Lumen 7.0

Thank you.


Solution

  • Please try this:

    //Try
    $result = DB::table('Users')
        ->select(DB::raw('CASE WHEN user_status=''new'' THEN ''New''  ELSE ''Expired'' END AS new_status'))
        ->where('user_id', 'A1')        
        ->get();
    
    //Try2
    $result = DB::table('Users')
        ->select(DB::raw("(CASE WHEN (user_status='new') THEN 'New'  ELSE 'Expired' END) AS new_status"))
        ->where('user_id', 'A1')        
        ->get();