Issue
I am trying to get latest messages from table 'messages' for inbox The chat is between user and owner of the item (listed on my portal) I want to get unique data with item_id
My code is
public function inbox()
{
// $inbox = ChatMessage::distinct('item_id')->where('incoming_msg_id', auth()->user()->id)->orWhere('outgoing_msg_id', auth()->user()->id)->orderBy('msg_id', 'DESC')->get();
$inbox = Message::where('incoming_msg_id', auth()->user()->id)->orWhere('outgoing_msg_id', auth()->user()->id)->latest('msg_id')->get()->unique('item_id');
return $this->sendResponse($inbox,'Chat');
}
Result is perfect just i need is non-associative/non-object array.
Current output
{
"success": true,
"data": {
"0": {
"msg_id": 68,
"incoming_msg_id": 0,
"outgoing_msg_id": 2,
"msg": "ok let me check",
"msg_for": "hadiya",
"item_id": "13",
"msg_at": "1 day ago"
},
"1": {
"msg_id": 62,
"incoming_msg_id": 0,
"outgoing_msg_id": 2,
"msg": "test msg",
"msg_for": "hadiya",
"item_id": "1",
"msg_at": "2 days ago"
}
},
"message": "Chat"
}
Expected Output
{
"success": true,
"data": [
{
"msg_id": 68,
"incoming_msg_id": 0,
"outgoing_msg_id": 2,
"msg": "ok let me check",
"msg_for": "hadiya",
"item_id": "13",
"msg_at": "1 day ago"
},
{
"msg_id": 62,
"incoming_msg_id": 0,
"outgoing_msg_id": 2,
"msg": "test msg",
"msg_for": "hadiya",
"item_id": "1",
"msg_at": "2 days ago"
}
],
"message": "Chat"
}
Thanks
Solution
I got the solution after lots of revisions. I got the distinct data in the best json format I was looking for...
$inbox = ChatMessage::select('msg_id','incoming_msg_id','outgoing_msg_id','msg','msg_for','item_id','msg_at')->groupBy('item_id')->where('incoming_msg_id', auth()->user()->id)->orWhere('outgoing_msg_id', auth()->user()->id)->get();
return $this->sendResponse($inbox,'Inbox');
Explanation : In Laravel 8 there is a function known as groupBy()
which is use for getting distinct results.
Check the link here for more information.
Answered By - Rizwan Patel
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.