Laravel Chat with Pivot Table how to return same users to same chat

点点圈 提交于 2019-12-24 08:50:03

问题


I am Developing a chat system , I have three tables (users , chats , user_chat) where is the user chat is the pivot table , I want to check every time that same users want to communicate to back to there chat room and don't create a new chat room

like

thats means that whenever **user_id:15** and **user_id:20** wish to communicate return them to **chat_room:1** and not create a new one how to do it I already tried array_intersect() but i didn't get any result

public function store(Request $requests){
//$requests->user()->id;
$data = $requests->all();
$username1 = User::select('username')->where('id',auth()->guard('api')->user()->id )->first();
$username2 = User::select('username')->where('id',$data['recever_id'] )->first();
$user1Conve[] = Conversation::where('user_id' , '=',auth()->guard('api')->user()->id )->select('chat_room_id')->get();
$user2Conve[] = Conversation::where('user_id' , '=',$data['recever_id'] )->select('chat_room_id')->get();
$result = array_intersect($user2Conve, $user1Conve);
if (count($result) == 0) {

    $chatroom = ChatRoom::create([
        'room_name' => 'محادثة بين' . $username1->username . ' و ' . $username2->username . '', 'sender_id' => auth()->guard('api')->user()->id

    ]);
    $lastId = (int)$chatroom->id;

    Conversation::create(['chat_room_id' => $lastId, 'user_id' => auth()->guard('api')->user()->id]);
    Conversation::create(['chat_room_id' => $lastId, 'user_id' => $data['recever_id']]);

    $message = Messages::create(
        ['message' => $data['message'],
            'user_room_id' => $lastId,
            'user_id' => auth()->guard('api')->user()->id,
        ]);
    $success['chat_room_id'] = $chatroom->id;
    $success['arrayIntersct'] = $result;
    $pusher = new Pusher("418914066f12eac2d5fd", "6e1b5e98b06d7d3ebd7a", "449820", array('cluster' => 'ap2'));
    $pusher->trigger('my-channel', 'my-event', array('message' => $message->message));
}
else {

}

  return response()->json(['code'=>'success','success'=>$success], $this->successStatus);

}


回答1:


array_intersect serches for all of the values in array1 whose values exist in array two, So I think you should use it with inversed arrays too:

$result1 = array_intersect($user1Conve,$user2Conve);
$result2 = array_intersect($user2Conve, $user1Conve);
if (count($result1) == 0 && count($result2) == 0) {
......


来源:https://stackoverflow.com/questions/48971202/laravel-chat-with-pivot-table-how-to-return-same-users-to-same-chat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!