เรียนคอร์ดออนไลน์กับเราวันนี้! ????

22 Jan 2025

public function addComment($postId)
{
    // Check if the user is logged in
    if (!session()->get('user_id')) {
        return redirect()->to('/auth/login');
    }

    // Validate comment input
    $content = $this->request->getPost('content');
    if (empty($content)) {
        return redirect()->back()->with('error', 'โปรดกรอกความคิดเห็น');
    }

    // Begin database transaction for consistency
    $db = \Config\Database::connect();
    $db->transStart();

    // Insert the comment into the database
    $this->commentModel->save([
        'post_id' => $postId,
        'author_id' => session()->get('user_id'),
        'content' => $content,
        'status' => 'approved', // Default to approved
    ]);

    // Increment comment_count in posts table
    $postModel = new \App\Models\PostModel();
    $postModel->where('id', $postId)->set('comment_count', 'comment_count + 1', false)->update();

    // Commit transaction
    $db->transComplete();

    if ($db->transStatus() === false) {
        // Rollback and handle error
        return redirect()->back()->with('error', 'เกิดข้อผิดพลาดในการเพิ่มความคิดเห็น');
    }

    return redirect()->back()->with('success', 'ความคิดเห็นของคุณถูกโพสต์แล้ว');
}

ความคิดเห็น

ยังไม่มีความคิดเห็น

เข้าสู่ระบบ เพื่อแสดงความคิดเห็น