Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

LaraBABA's avatar

From normal DB query to Eloquent

Hi all,

I would like to know which steps would you use to convert this into an Eloquent query please, do you know of any convertor? I have 2 problems in keeping this query this way: 1)I need pagination 2)I need to use ->where() as

                ->when($variable, function ($query) use ($variable) {
                   $query->where('C1.sent', '=', $variable);
                })
DB::select("SELECT
  C1.chat_title,
  C1.chat_object,
  C1.created_at,
  C1.id,
  MAX(C1.message) AS messages,
  C2.unread,
  C1.group_id
FROM chats C1
  INNER JOIN (SELECT
      C2.created_at,
      C2.chat_object,
      SUM(IF(C2.admin_read = 0, 1, 0)) AS unread
    FROM chats C2
    GROUP BY C2.chat_object) C2
    ON C1.chat_object = C2.chat_object
WHERE C1.group_id = 82
GROUP BY C1.chat_object,
         C1.group_id
ORDER BY C1.id DESC")

Any ideas please? I tried to manually convert this query to Eloquent but failed to get anything working. I have CHAT model already.

Thanks all.

0 likes
7 replies
LaraBABA's avatar

Ok I got it:

DB::table(DB::raw('chats C1'))
->select('C1.chat_title','C1.chat_object','C1.created_at','C1.id',DB::raw('MAX(C1.message) AS messages'),'C2.unread','C1.group_id')
->join(DB::raw('(SELECT
      C2.created_at,
      C2.chat_object,
      SUM(IF(C2.admin_read = 0, 1, 0)) AS unread
    FROM chats C2
    GROUP BY C2.chat_object) C2'),'C1.chat_object','=','C2.chat_object')
                ->where('C1.group_id','=',82)
                ->groupBy(['C1.chat_object','C1.group_id'])
                ->orderBy('C1.id','DESC')
                ->paginate();

I cannot believe how much I struggled for a full day on this!

1 like
LaraBABA's avatar

@tisuchi I had tried this one but it was not working, especially on the join part :-)

But got it now, thank you so much for your help.

LaraBABA's avatar

I had to remove the best answer, I just noticed that : MAX(C1.message) AS messages goes not actually show the latest message. It was a pure coincidence that it did because my messages had numbers in the fields :-(

sr57's avatar

Hi @user476820

You have to remove the Best Answer from the previous post, your MAX(C1.message) does not work in the original request for the same reason I wrote in my first answer.

Please or to participate in this conversation.