/** * Stores a new message thread * * @return mixed */ public function store() { $input = Input::all(); $recipient_id = $input['recipient']; $sender_id = JWTAuth::parseToken()->authenticate()->id; if ($sender_id == $recipient_id) { return response()->json(['success' => 'false', 'message' => 'Error. Your ID and receipient ID cannot be same.']); } if ($sender_id > $recipient_id) { $subject = $recipient_id . ' ' . $sender_id; $thread = Thread::firstOrCreate(['subject' => $subject]); } else { $subject = $sender_id . ' ' . $recipient_id; $thread = Thread::firstOrCreate(['subject' => $subject]); } // Message Message::create(['thread_id' => $thread->id, 'user_id' => $sender_id, 'body' => $input['message']]); if (!$thread->participantsUserIds()->unique()->search($recipient_id)) { //if first time thread is created, no record of participants in thread // Sender Participant::create(['thread_id' => $thread->id, 'user_id' => $sender_id, 'last_read' => new Carbon()]); // Recipients $thread->addParticipants([$recipient_id]); } return response()->json(['success' => 'true', 'message' => 'Message sent.', 'thread_id' => $thread->id]); }