/** * Subscribe to a post to receive e-mail notifications * * @return mixed */ public function indexAction() { $this->view->disable(); $this->setJsonResponse(); if (!$this->request->isPost()) { return false; } //Find the post by Id $post = Posts::findFirstById($this->request->getPost('objectId')); if (!$post) { $this->jsonMessages['messages'][] = ['type' => 'error', 'content' => 'The Post does not exist']; return $this->jsonMessages; } /** * Sometime We need to get object User login, so I do check user like below * By the way, you can checking session * * {code} Users::findFirstById($this->auth->getAuth()['id'] {/code} */ $userId = $this->auth->getAuth()['id']; if (!$userId) { $this->jsonMessages['messages'][] = ['type' => 'error', 'content' => 'You must log in first to subscribe post']; return $this->jsonMessages; } $subscription = PostsSubscribers::findFirst(['postsId = ?0 AND usersId = ?1', 'bind' => [$post->getId(), $userId]]); if (!$subscription) { $subscription = new PostsSubscribers(); $subscription->setPostsId($post->getId()); $subscription->setUsersId($userId); if (!$subscription->save()) { foreach ($subscription->getMessages() as $message) { $this->logger->error('Subscribe save false ' . $message . __LINE__ . 'and' . __CLASS__); } return false; } $this->jsonMessages['messages'][] = ['type' => 'info', 'content' => 'You have just subscribe post', 'flag' => 1]; return $this->jsonMessages; } else { //unsubsribe posts if (!$subscription->delete()) { foreach ($subscription->getMessages() as $message) { $this->logger->error('Unsubscribe delete false ' . $message . __LINE__ . 'and' . __CLASS__); } return false; } $this->jsonMessages['messages'][] = ['type' => 'info', 'content' => 'You have just unsubscribe post']; return $this->jsonMessages; } }