/** * Store a newly chat. * * @return Response */ public function create() { if (!is_null($user = User::find((int) Input::get('user_id')))) { if (!Auth::user()->isBlocked($user->id)) { $result = DB::select('select c.chat_id, count(c.chat_id) as count ' . 'from chats_members c where c.chat_id in (select b.chat_id from chats_members b where b.chat_id in (select a.chat_id from chats_members a where a.user_id = ?) and b.user_id = ?) ' . 'group by c.chat_id having c.count = 2 limit 1;', array(Auth::user()->id, $user->id)); if (count($result) > 0) { $chatId = $result[0]->chat_id; $chat = Chat::find($chatId); } else { $chat = new Chat(); $chat->owner_id = Auth::user()->id; $chat->topic = ''; $chat->save(); $chatId = $chat->id; $chatMember = new ChatMember(); $chatMember->chat_id = $chatId; $chatMember->user_id = Auth::user()->id; $chatMember->save(); $chatMember = new ChatMember(); $chatMember->chat_id = $chatId; $chatMember->user_id = $user->id; $chatMember->save(); $chatHystory = new ChatHistory(); $chatHystory->chat_id = $chatId; $chatHystory->event = 'created'; $chatHystory->save(); $chat = Chat::find($chat->id); } return $this->respond(array('chat_id' => $chat->id, 'owner_id' => $chat->owner_id, 'topic' => $chat->topic, 'timestamp' => $chat->getTimestamp(), 'users' => $chat->getUsersArray())); } else { return $this->respondInsufficientPrivileges('Can\'t send message to the user'); } } else { return $this->respondNotFound('User doesn\'t exist'); } }