phpmysqllaraveleloquent

Fetch recent chat entries per user using Laravel Eloquent


I am trying to create chat for my website in Laravel. I am selecting the recent chats for the user where user can see the list of users with whom he can chat.

Here are my query:

$data = [];
$chatusers = Chat::latest()->get(['reciver_id']);
$chatusers = collect($chatusers)->unique()->values()->all(); 

foreach ($chatusers as $user) {
    if ($user['reciver_id'] >= 5000) {
        $message = Chat::where('reciver_id', $user['reciver_id'])
            ->latest()
            ->first();
        
        array_push($data, $message);
    } else {
        $message = Chat::where('sender_id', $user['reciver_id'])
            ->orWhere('reciver_id', $user['reciver_id'])
            ->latest()
            ->first();
     
        array_push($data, $message);
    }
}

Here I am attaching screenshots of DB tables: https://i.sstatic.net/dKEKs.jpg

Here is screen for chat-list:- https://i.sstatic.net/6VAmH.jpg

I am not managing relationship.


Solution

  •    $login_user_id = 1; // use auth user_id
       $chat = Chat::where(function($q) use($login_user_id){
            $q->where('sender_id',$login_user_id)>orWhere('receiver_id',$login_user_id);
            $q->where('receiver_id',$login_user_id)->orWhere('sender_id',$login_user_id);
        })->orderBy('created_at','desc')->get()->toArray();
            $other_user_id = [];
            $message = [];
       foreach ($chat as $key => $value) {
          if(in_array($value->sender_id, $other_user_id) || in_array($value->receiver_id, $other_user_id)){
                    continue;
                }
                if($value->sender_id != $login_user_id){
                    $other_user_id[] = $value->sender_id;
                }else{
                    $other_user_id[] = $value->receiver_id;
                }
    
                $message[] = $value;
    
            }
            print_r($message);
    

    You have to add table to manage unread messages.