Skip to content
Advertisement

Laravel using a case statement

I’m trying to retrieve all messages of a conversation and display it’s status (read or unread). With a CASE I try to read the message.read property (boolean) and process it to a string.

$messages = DB::table('conversation_message')
->select(
    'messages.id as message_id',
    'messages.created_at as send_at',
    'messages.user_id as from_id',
    'messages.body as body',
    'conversations.id as conversation',
    DB::raw('(CASE WHEN messages.read = 1 THEN read ELSE unread END) AS status')
)
->leftjoin('messages', 'messages.id', '=', 'conversation_message.message_id')
->leftjoin('conversations', 'conversations.id', '=', 'conversation_message.conversation_id')
->orderBy('send_at', 'asc')
->get();

Without the CASE, the query works fine but with the case I recieve a Syntax error or access violation: 1064 near 'read.

Advertisement

Answer

Solved it by placing both the outcomes read and unread in double quotes.

$messages = DB::table('conversation_message')
->select(
    'messages.id as message_id',
    'messages.created_at as send_at',
    'messages.user_id as from_id',
    'messages.body as body',
    'conversations.id as conversation',
    DB::raw('(CASE WHEN messages.read = 1 THEN "read" ELSE "unread" END) AS status')
)
->leftjoin('messages', 'messages.id', '=', 'conversation_message.message_id')
->leftjoin('conversations', 'conversations.id', '=', 'conversation_message.conversation_id')
->orderBy('send_at', 'asc')
->get();

Now I can use the status directly as a css class!

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement