Web Development Handbook

Web Development Handbook

Development is fun in a funny way

How to create a comment system using Laravel Livewire: Part 3

How to create a comment system using Laravel Livewire: Part 3

0 votes
0 votes
0 comments
266 views
Share

By Nihar Ranjan Das, Published on June 6th 2023 | 8 mins, 703 words

In the previous article, I talked about the Comment creation form. In this article, we
will discuss the Comments component of the entire process.

The Comments Component

This component has two files. One is the Comments class and comments.blade.php view file. We will talk about the class.

// app/Http/Livewire/Comments.php

namespace App\Http\Livewire;
 
use App\Models\Comment;
use App\Models\Post;
use Illuminate\Database\Eloquent\Collection;
use Livewire\Component;
 
class Comments extends Component
{
    public Post $post;
    public Collection $comments;

    public $listeners = [
        'commentCreated' => 'commentCreated',
        'commentDeleted' => 'commentDeleted',
    ];

    public function mount(Post $post)
    {
        $this->post = $post;
        $this->comments = $this->getComments();
    }

    public function render()
    {
        $comments = $this->comments;
        return view('livewire.comments', compact('comments'));
    }

    public function commentCreated(int $id)
    {
        $comment = Comment::query()->find($id);
        if (!$comment->parent_id) {
            $this->comments = $this->comments->prepend($comment);
        }
    }

    public function commentDeleted(int $id)
    {
        $this->comments = $this->comments->reject(function ($comment, int $key) use ($id) {
            return $comment->id == $id;
        });
    }

    private function getComments(): Collection|array
    {
        return Comment::query()
            ->with([
               'user',
               'replies'
            ])
            ->where('post_id', $this->post->id)
            ->whereNull('parent_id')
            ->orderByDesc('created_at')
            ->get();
    }
}

The Comments block will handle the listing of comments in the Comment System. This component fetches the comments from the server and renders those on the web page

Properties

This class declares two public properties including $post, and $comments.

  • $post property contains the Post data. This means the post where the user wants to create comments
  • $comments is the collection of comments. 

In the Livewire component, there is one property called $listeners which contains some events emitted from child components.

There are several methods here but will discuss only commentCreated, commentDeleted, and getComments 

commentCreated method

public function commentCreated(int $id)
{
    $comment = Comment::query()->find($id);
    if (!$comment->parent_id) {
        $this->comments = $this->comments->prepend($comment);
    }
}

This will call after the commentCreated event emits from the CommentCreate component. This method is responsible for handling events when a comment is created

  1. The method takes an integer parameter $id, which represents the ID of a newly created comment.
  2. It uses the Comment model to query the database and find the comment with the specified ID using the Comment::query()->find($id) method. The retrieved comment is assigned to the $comment variable.
  3. It checks if the retrieved comment does not have a parent_id value. This condition implies that the comment is a top-level comment (not a reply to another comment).
    • If the condition is true (the comment does not have a parent_id), it proceeds to the next step.
    • If the condition is false (the comment has a parent_id), the code does not execute the following lines.
  4. If the comment is a top-level comment, it modifies the $comments property (assuming it exists) by prepending the newly created comment to the existing collection of comments. The prepend() method adds an item to the beginning of the collection.
    • This suggests that the $comments property is likely an array or a collection of comments, and the newly created comment is added at the beginning to display it as the most recent comment.


commentDeleted method

public function commentDeleted(int $id)
{
    $this->comments = $this->comments->reject(function ($comment, int $key) use ($id) {
        return $comment->id == $id;
    });
}

The commentDeleted method is responsible for handling events emitted from the CommentItem component when a comment is deleted. It receives the ID of the deleted comment, iterates over the existing comments collection, and removes the comment with the matching ID from the collection. This ensures that the deleted comment is no longer included in the displayed comments.

  1. The method takes an integer parameter $id, which represents the ID of the comment to be deleted.
  2. It modifies the $comments property (assuming it exists) by rejecting specific comments from the collection. The reject() method is used to iterate over each element of the collection and remove elements that meet certain conditions.


In the next article, we will talk about the CommentItem component. If you are interested, click here. If you have any questions about this article, you can leave a comment below.  

If you like our tutorial, do make sure to support us by buy us a coffee ☕️

Comments

Default avatar

Are you interested to learn more?

Be notified on future content. Never spam.