首页 > 解决方案 > 在 Laravel 帖子中限制评论

问题描述

所以这就是问题所在,我有发布和评论的应用程序。但我想限制每个用户的评论,所以如果有 1 个帖子,每个用户只有 1 个评论。可能吗 ?

这是我的store功能CommentController

public function store(Request $request, $post)
{
    $this->validate($request, array(
        'title' => 'required|max:200',
        'desc' => 'required|max:800'
    ));
    $comments = new Comment();
    $comments->id_user = Auth::id();
    $comments->id_post = $post;
    $comments->title = $request->A;
    $comments->desc = $request->B;
    $comments->save();
    return redirect()->route('controller.index');
}

我可以在这个store函数中添加什么查询来限制用户在 1 个帖子中只能评论一次。谢谢大家希望你能帮助我。

标签: phplaravelcontroller

解决方案


您需要检查用户和帖子的评论是否已经存在,这非常简单,如下所示:

if (! Comment::where('id_user', $userId)->where('id_post', $postId)->exists()) {
   //save the comment
} else {
   // do not save the comment
}

在您的情况下$userId可能是Auth::user()->id,并且 $postId 是$post->id


推荐阅读