PHP code example of newway-solutions / laravel-comments

1. Go to this page and download the library: Download newway-solutions/laravel-comments library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

newway-solutions / laravel-comments example snippets




return [
    /*
     * The comment class that should be used to store and retrieve
     * the comments.
     */
    'comment_class' => \NewWaySo\Comments\Comment::class,

    /*
     * The user model that should be used when associating comments with
     * commentators. If null, the default user provider from your
     * Laravel authentication configuration will be used.
     */
    'user_model' => null,

    /**
     * Determines if replies will be deleted when comments are deleted
     */
    'delete_replies_along_comments' => false,
];



namespace App\Models;

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

class Post extends Model
{
    use HasComments;
    
    // Your model code here...
}



namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use NewWaySo\Comments\Contracts\Commentator;
use NewWaySo\Comments\Traits\CanComment;

class User extends Authenticatable implements Commentator
{
    use CanComment;
    
    /**
     * Check if a comment for a specific model needs to be approved.
     */
    public function needsCommentApproval($model): bool
    {
        // Return false if the user's comments should be auto-approved
        // Return true if the user's comments need manual approval
        return false; // Auto-approve comments from this user
    }
}

// Add a comment as the currently authenticated user
$post = Post::find(1);
$comment = $post->comment('This is a great post!');

// Add a comment as a specific user
$user = User::find(1);
$comment = $post->commentAsUser($user, 'This is a great post!');

// Add a comment without a user (anonymous comment)
$comment = $post->commentAsUser(null, 'Anonymous comment');

$post = Post::find(1);

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

// Get only approved comments
$approvedComments = $post->comments()->approved()->get();

// Get comments with their commentators (users)
$commentsWithUsers = $post->comments()->with('commentator')->get();

$post = Post::find(1);
$comment = $post->comment('This is the main comment');

// Reply to a comment
$reply = $post->replyToComment($comment, 'This is a reply to the comment');

// Reply as a specific user
$user = User::find(1);
$reply = $post->replyToComment($comment, 'This is a reply', $user);

// Get replies for a comment
$replies = $comment->replies;

// Get parent comment of a reply
$parentComment = $reply->parent;

$comment = Comment::find(1);

// Approve a comment
$comment->approve();

// Disapprove a comment
$comment->disapprove();

// Check if comment is approved
if ($comment->is_approved) {
    // Comment is approved
}

$comment = Comment::find(1);

// Delete a comment
$comment->delete();

// If you want replies to be deleted along with the comment,
// set this in your config file:
// 'delete_replies_along_comments' => true,

// Get only approved comments
$approvedComments = Comment::approved()->get();

// Get comments for a specific model
$post = Post::find(1);
$postComments = $post->comments()->approved()->latest()->get();

$comment = Comment::find(1);

// Get the model that was commented on
$commentedModel = $comment->commentable;

// Get the user who made the comment
$user = $comment->commentator;

// Get replies to this comment
$replies = $comment->replies;

// Get parent comment (if this is a reply)
$parent = $comment->parent;



namespace App\Listeners;

use NewWaySo\Comments\Events\CommentAdded;

class SendCommentNotification
{
    public function handle(CommentAdded $event)
    {
        $comment = $event->comment;
        
        // Send notification email
        // Log the comment
        // Update statistics
        // etc.
    }
}



namespace App\Listeners;

use NewWaySo\Comments\Events\CommentDeleted;

class HandleCommentDeletion
{
    public function handle(CommentDeleted $event)
    {
        $comment = $event->comment;
        
        // Clean up related data
        // Update statistics
        // Send notifications
        // etc.
    }
}

protected $listen = [
    \NewWaySo\Comments\Events\CommentAdded::class => [
        \App\Listeners\SendCommentNotification::class,
    ],
    \NewWaySo\Comments\Events\CommentDeleted::class => [
        \App\Listeners\HandleCommentDeletion::class,
    ],
];



// Models
class Post extends Model
{
    use HasComments;
    
    protected $fillable = ['title', 'content'];
}

class User extends Authenticatable implements Commentator
{
    use CanComment;
    
    public function needsCommentApproval($model): bool
    {
        // Auto-approve comments from verified users
        return !$this->email_verified_at;
    }
}

// Controller
class PostController extends Controller
{
    public function show(Post $post)
    {
        $post->load([
            'comments' => function ($query) {
                $query->approved()
                      ->whereNull('parent_id') // Only top-level comments
                      ->with(['commentator', 'replies.commentator'])
                      ->latest();
            }
        ]);
        
        return view('posts.show', compact('post'));
    }
    
    public function storeComment(Request $request, Post $post)
    {
        $request->validate([
            'comment' => '
bash
php artisan vendor:publish --provider="NewWaySo\Comments\CommentsServiceProvider" --tag="migrations"
php artisan migrate
bash
php artisan vendor:publish --provider="NewWaySo\Comments\CommentsServiceProvider" --tag="config"
blade
{{-- Display comments --}}
@foreach($post->comments as $comment)
    <div class="comment">
        <div class="comment-header">
            <strong>{{ $comment->commentator->name ?? 'Anonymous' }}</strong>
            <small>{{ $comment->created_at->diffForHumans() }}</small>
        </div>
        <div class="comment-body">
            {{ $comment->comment }}
        </div>
        
        {{-- Display replies --}}
        @foreach($comment->replies as $reply)
            <div class="reply">
                <div class="reply-header">
                    <strong>{{ $reply->commentator->name ?? 'Anonymous' }}</strong>
                    <small>{{ $reply->created_at->diffForHumans() }}</small>
                </div>
                <div class="reply-body">
                    {{ $reply->comment }}
                </div>
            </div>
        @endforeach
    </div>
@endforeach

{{-- Comment form --}}
<form method="POST" action="{{ route('posts.comments.store', $post) }}">
    @csrf
    <div class="form-group">
        <textarea name="comment" class="form-control" placeholder="Add a comment..."></textarea>
    </div>
    <button type="submit" class="btn btn-primary">Post Comment</button>
</form>