Web Development Handbook

Web Development Handbook

Development is fun in a funny way

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

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

0 votes
0 votes
0 comments
290 views
Share

By Nihar Ranjan Das, Published on June 7th 2023 | 11 mins, 1045 words

In the previous article, I shared the full source code of the Comment system. In this article, we
will discuss the 1st component of the entire process. A Comment Create form is the first thing
we need first to develop a comment system.

The Comment Create Component

This component has two files. One is the CommentCreate class and comment-create.blade.php view file. We will talk about the class.

// app/Http/Livewire/CommentCreate.php

namespace App\Http\Livewire;
 
use App\Models\Comment;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
 
class CommentCreate extends Component
{
    public ?User $user = null;
    public ?Comment $commentModel = null;
    public string $comment = '';
    public int $postId;
    public ?int $parentId = null;
    public ?string $message = null;
    public bool $showProfile = true;

    protected array $rules = [
        'comment' => 'required|string'
    ];

    protected array $messages = [
        'comment.required' => 'Comment is required',
        'comment.string' => 'Invalid comment',
    ];

    public function mount(
        int $postId,
        $commentModel = null,
        ?int $parentId = null,
        bool $showProfile = true
    )
    {
        if (Auth::check()) {
            $this->user = Auth::user();
        }
        $this->postId = $postId;
        $this->parentId = $parentId;
        $this->commentModel = $commentModel;
        $this->comment = $this->commentModel?->comment ?? '';
        $this->showProfile = $showProfile;
    }

    public function resetForm()
    {
        $this->comment = '';
        $this->parentId = null;
        $this->commentModel = null;
        $this->emitUp('hideCommentForm');
    }

    public function createComment()
    {
        $this->validate();
        if (!\auth()->check()) {
             return $this->redirect(route('login'));
        }
        if ($this->commentModel && $this->commentModel->comment) {
             if ($this->user->id != $this->commentModel->user_id) {
                  return response('You are allowed to perform this action.')->status(403);
             }
             $this->commentModel->comment = $this->comment;
             $this->commentModel->save();
             $this->emitUp('commentUpdated');
        } else {
            Comment::query()
               ->create([
                   'comment' => $this->comment,
                   'post_id' => $this->postId,
                   'user_id' => $this->user->id,
                   'parent_id' => $this->parentId
               ]);
            $this->emitUp('commentCreated', $comment->id);
        }

        $this->comment = '';
    }

    public function render()
    {
        return view('livewire.comment-create');
    }
}

The CommentCreate block will handle the creation and editing of comments in the Comment
System. This component is used for Comment creation, edit & reply.

Properties

This class declares several public properties including $user, $commentModel, $comment,
$postld, $parentld, $message, and $showProfile.

  • $user object is the currently logged-in user who wants to create a comment.
  • $commentModel object is the parent comment when we want to create a reply or edit a comment.
  • $comment is the text we want to create in a post.
  • $postld is the id of the post.
  • $parentld is the parent comment id when we want to create a reply.
  • $message is the alert message after creating a comment.
  • $showProfile is a boolean param that controls the user avatar field of the comment form when we want to create a reply or edit a comment.  

In the Livewire component, there are two properties called $rules & $messages. We can define some validation rules & messages in those variables which will be used while validating a form submission.


Here mount & render are the Livewire methods. For our system purpose, we created resetForm & createComment

mount method

In Livewire components, the mount method is used instead of the __construct method. Like a controller, we can inject dependencies by adding type-hinted parameters before passed-in ones. Here we injected 4 parameters. $postId is required but $commentModel, $parentId, and $showProfile are optional

render method

In Livewire components, the render method is used to load the target blade file and render it.

commentCreate method

public function createComment()
    {
        $this->validate();
        if (!\auth()->check()) {
             return $this->redirect(route('login'));
        }
        if ($this->commentModel && $this->commentModel->comment) {
             if ($this->user->id != $this->commentModel->user_id) {
                  return response('You are allowed to perform this action.')->status(403);
             }
             $this->commentModel->comment = $this->comment;
             $this->commentModel->save();
             $this->emitUp('commentUpdated');
        } else {
            Comment::query()
               ->create([
                   'comment' => $this->comment,
                   'post_id' => $this->postId,
                   'user_id' => $this->user->id,
                   'parent_id' => $this->parentId
               ]);
            $this->emitUp('commentCreated', $comment->id);
        }

        $this->comment = '';
    }

This method is responsible for the comment creation, edit & reply. Let's understand the code line by line.

  1. It first calls the validate() method, which presumably performs some form of validation using the rules & messages property data on the data before proceeding.
  2. It checks if the user is not logged in by using the auth()->check() function. If the user is not logged in, it redirects them to the login page using the redirect() function and the route() helper to generate the login route.
  3. If the user is logged in, it checks if the $commentModel property exists and if it has a non-empty comment property.
    • If both conditions are met, it checks if the currently authenticated user's ID ($this->user->id) is not equal to the ID of the user who created the comment ($this->commentModel->user_id).
      • If the condition is true, it returns a response with the message "You are allowed to perform this action." and the HTTP status code 403 (Forbidden).
      • If the condition is false, it updates the comment property of the $commentModel object with the new comment value ($this->comment), saves the changes to the database, and emits an event named 'commentUpdated' to notify any listening components.
    • If the conditions for the $commentModel check fail (the $commentModel is null or its comment property is empty), it creates a new comment using the Comment::query()->create() method.
      • The comment is created with the values of comment, post_id, user_id, and parent_id properties, which are assigned from the corresponding properties ($this->comment, $this->postId, $this->user->id, and $this->parentId).
      • After creating the comment, it emits an event named 'commentCreated' with the ID of the newly created comment ($comment->id) to notify the Comments component.
  4. Finally, it sets the comment property to an empty string, presumably to clear the input field after the comment creation/update/reply is complete.


In the next article, we will talk about the Comments 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.