Skip to content
Advertisement

Limit Comment in Post Laravel

So this is the problem, I have application with post and comment. But I want to limit the comment per user, So if there is 1 post only 1 comment per user. Is it possible ?

Here is my store function in 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');
}

What query can I add in this store function to limit the user to only comment once in 1 post. Thanks guys hope you can help me.

Advertisement

Answer

It’s very simple you need to check if a comment for a user and post already exists like this:

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

In your case $userId may be Auth::user()->id, and the $postId is $post->id.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement