Your eloquent pagination run on ChatRoom table Not on messages.
So you can try another ways to load your message under chatroom.
- If you have a lot of chatroom and want to paginate both chatroom and their messages, you can paginate chatroom (without join to messages) and run eloquent for each chatroom messages separately.
- you can also use lazy load for messages on view but you must control messages paginate yourself
-------------EDITED-------------
Show chatroom with new messages:
Laravel <6
ChatRoom::select(['chat_rooms.*', 'chats.created_at as c'])
->join(DB::raw("(SELECT chats.room_id, max(chats.created_at) as created_at
FROM chats
GROUP BY room_id
ORDER BY created_at DESC
) as chats"), function ($join) {
$join->on("chat_rooms.id", "=", "chats.room_id");
})
->orderBy('c', 'DECS')
->paginate(5);
Laravel >=6
$chatQuery = Chat::selectRaw("chats.room_id, max(chats.created_at) as created_at")
->groupBy("chats.room_id")
->orderBy("created_at", "desc");
ChatRoom::select(['chat_rooms.*', 'chats.created_at as c'])
->joinSub($chatQuery, 'chats', function ($join) {
$join->on('chat_rooms.id', '=', 'chats.room_id');
})
->orderBy('c','DECS')
->paginate(5);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…