protected function createMessage($from, $msg) { echo sprintf('User %d sending message "%s" to user %d' . "\n", $from->userId, $msg->message, $msg->userTo); $dialog = new Dialog(); $dialog->from = $from->userId; $dialog->to = $msg->userTo; if ($dialog->validate()) { if (($existedDialog = Dialog::byUsers($dialog->from, $dialog->to)->first()) === null) { $dialog->save(); $existedDialog = $dialog; } $message = new Message(); $message->from = $from->userId; $message->dialog_id = $existedDialog->id; $message->text = $msg->message; if ($message->validate()) { $message->save(); foreach ($this->clients as $client) { if ($client->userId == $from->userId || $client->userId == $msg->userTo || $client->isAdmin === true) { $view = view('chat._message', ['messages' => [$message], 'isAdmin' => $client->isAdmin]); $sendData = ['action' => Message::CREATE_ACTION_NAME, 'html' => $view->render()]; $client->send(json_encode($sendData)); } } } } }
public function show($id) { (new Message())->readOpenMessage($id); $messages = Message::where('dialog_id', $id)->orderBy('created_at', 'desc')->get(); $user_id = Dialog::where('total', $id)->where('user_id', '!=', \Auth::user()->id)->first()->user_id; $sender = User::find($user_id); return view('show', ['messages' => $messages, 'sender' => $sender, 'id' => $id]); }
public function loadHistory(Request $request, $from, $to = null) { $currentUser = $this->auth->user(); if ($currentUser->is_admin) { if ($to === null) { abort(404); } } else { $to = $currentUser->id; } if (($dialog = Dialog::byUsers($from, $to)->first()) === null) { $messages = []; } else { $messages = Message::byDialog($dialog->id)->orderBy('created_at', 'asc')->get(); } $data = ['messages' => $messages, 'isAdmin' => $currentUser->is_admin]; if ($request->ajax()) { $viewName = 'chat._message'; } else { $viewName = 'chat.history'; $data['currentUser'] = $currentUser; } return view($viewName, $data); }