DEV Community

Cover image for Automate comment system in Laravel: A comprehensive guide
Nikola Perišić
Nikola Perišić

Posted on

Automate comment system in Laravel: A comprehensive guide

👋 Hello everyone!

🚀 Today, let's delve into the world of Laravel comments using the fantastic package from beyondcode.

📁 This package allows seamless integration of commenting functionality into your Laravel applications. Users can comment on various entities like posts, articles, or any other model in your application.

Let's get started! 🌟


Installation via Composer

composer require beyondcode/laravel-comments

The package will automatically register itself.

You can publish the migration with:

php artisan vendor:publish --provider="BeyondCode\Comments\CommentsServiceProvider" --tag="migrations"
Enter fullscreen mode Exit fullscreen mode

After the migration has been published you can create the media-table by running the migrations:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

You can publish the config-file with:

php artisan vendor:publish --provider="BeyondCode\Comments\CommentsServiceProvider" --tag="config"
Enter fullscreen mode Exit fullscreen mode

Usage

Registering Models

To let your models be able to receive comments, add the HasComments trait to the model classes. 🔍

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use BeyondCode\Comments\Traits\HasComments;

class Post extends Model
{
    use HasComments;
    ...
}
Enter fullscreen mode Exit fullscreen mode

Commenting on entities

To create a comment on your commentable models, you can use the comment method. It receives the string of the comment that you want to store. 📌

use App\Models\Post;
use BeyondCode\Comments\Traits\HasComments;

class YourModel extends Model
{
    use HasComments;
}

$post = Post::find(1);

$post->comment('This is a comment');

$post->commentAsUser($user, 'This is a comment from someone else');

Enter fullscreen mode Exit fullscreen mode

Retrieving Comments

$post = Post::find(1);

// Retrieve all comments
$comments = $post->comments;

// Retrieve only approved comments
$approved = $post->comments()->approved()->get();
Enter fullscreen mode Exit fullscreen mode

Additional Resources

Check out the official README for more details and advanced usage.


👉 Stay tuned for more updates by following me on GitHub! 🔔

👉 Don't forget to share your thoughts and experiences in the comments below! 💬

Top comments (0)