I need help on to correct my implementation on validating the email if it’s already exists.
Anyone knows what’s wrong with my code? It is not validating this part. It will save even if the email already exists in db.
if ($existingFeedback->getId()) {
$result = ['success' => false, 'error' => __('Email already exists in the database.')];
$this->getResponse()->setBody(json_encode($result));
return;
}
public function execute()
{
$data = $this->getRequest()->getPostValue();
if (!$data) {
$this->_redirect('*/*/');
return;
}
// Validate email
if (empty($data['email'])) {
$result = ['success' => false, 'error' => __('Email is required.')];
$this->getResponse()->setBody(json_encode($result));
return;
}
// Check if email already exists
$existingFeedback = $this->customerFeedbackFactory->create()->getCollection()
->addFieldToFilter('email', $data['email'])
->getFirstItem();
if ($existingFeedback->getId()) {
$result = ['success' => false, 'error' => __('Email already exists in the database.')];
$this->getResponse()->setBody(json_encode($result));
return;
}
$customerFeedback = $this->customerFeedbackFactory->create();
$customerFeedback->setData('title', $data['title']);
$customerFeedback->setData('content', $data['content']);
$customerFeedback->setData('email', $data['email']);
$customerFeedback->save();
$result = ['success' => true];
$this->getResponse()->setBody(json_encode($result));
}