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)