PHP code example of andydefer / laravel-comments

1. Go to this page and download the library: Download andydefer/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/ */

    

andydefer / laravel-comments example snippets


'providers' => [
    // ...
    AndyDefer\LaravelComments\CommentsServiceProvider::class,
],

use AndyDefer\LaravelComments\Services\CommentService;

class PostController extends Controller
{
    public function store(CommentService $commentService)
    {
        $user = auth()->user();
        $post = Post::find(1);

        // Ajouter un commentaire
        $comment = $commentService->add(
            commenter: $user,      // Qui commente
            commentable: $post,    // Quoi est commenté
            content: 'Super article !'
        );

        return $comment;
    }
}

// Ajouter une réponse à un commentaire existant
$reply = $commentService->add(
    commenter: $user,
    commentable: $post,
    content: 'Merci pour ce retour !',
    parentId: $comment->id  // ID du commentaire parent
);

// Récupère uniquement les commentaires publiés par défaut
$comments = $commentService->get($post);

// Récupère tous les commentaires (incluant masqués et signalés)
$allComments = $commentService->get($post, false);

$replies = $commentService->getReplies($commentId);

$userComments = $commentService->getByCommenter($user);

$comment = $commentService->find($commentId);

$updated = $commentService->update($commentId, 'Nouveau contenu modifié');

$commentService->delete($commentId);

$hidden = $commentService->hide($commentId);
// Le statut passe à 'hidden'

$published = $commentService->publish($commentId);
// Le statut passe à 'published'

$flagged = $commentService->flag($commentId);
// Le statut passe à 'flagged'

// Compter les commentaires publiés d'un modèle
$count = $commentService->count($post);

// Compter tous les commentaires (incluant masqués et signalés)
$total = $commentService->count($post, false);

// Compter les commentaires signalés
$flaggedCount = $commentService->countFlagged();

// Compter les commentaires masqués
$hiddenCount = $commentService->countHidden();

// Compter les commentaires publiés
$publishedCount = $commentService->countPublished();

use AndyDefer\LaravelComments\Enums\CommentStatus;

$status = CommentStatus::PUBLISHED;

$status->getLabel();    // 'Publié'
$status->isPublished(); // true
$status->isHidden();    // false
$status->isFlagged();   // false

$comment = Comment::find(1);

// Accès sous forme de Value Objects
$createdAt = $comment->getCreatedAt();    // DateTimeVO
$updatedAt = $comment->getUpdatedAt();    // DateTimeVO
$metadata = $comment->getMetadata();      // StrictDataObject

// Relations
$commenter = $comment->commenter;    // Auteur (User, Admin, etc.)
$commentable = $comment->commentable; // Objet commenté (Post, Article, etc.)
$parent = $comment->parent;           // Commentaire parent
$replies = $comment->replies;         // Réponses (HasMany)

use AndyDefer\LaravelComments\Services\CommentService;
use AndyDefer\LaravelComments\Enums\CommentStatus;

class CommentController extends Controller
{
    public function __construct(
        private readonly CommentService $commentService
    ) {}

    public function store(Request $request, Post $post)
    {
        $comment = $this->commentService->add(
            commenter: $request->user(),
            commentable: $post,
            content: $request->input('content')
        );

        return response()->json($comment, 201);
    }

    public function index(Post $post)
    {
        $comments = $this->commentService->get($post);

        return response()->json($comments);
    }

    public function reply(Request $request, Post $post, Comment $parent)
    {
        $reply = $this->commentService->add(
            commenter: $request->user(),
            commentable: $post,
            content: $request->input('content'),
            parentId: $parent->id
        );

        return response()->json($reply, 201);
    }

    public function moderate(Comment $comment, string $action)
    {
        $result = match($action) {
            'hide' => $this->commentService->hide($comment->id),
            'flag' => $this->commentService->flag($comment->id),
            'publish' => $this->commentService->publish($comment->id),
            'delete' => $this->commentService->delete($comment->id),
            default => throw new \InvalidArgumentException('Invalid action')
        };

        return response()->json(['success' => true, 'comment' => $result]);
    }

    public function stats(Post $post)
    {
        return response()->json([
            'total' => $this->commentService->count($post, false),
            'published' => $this->commentService->count($post, true),
            'flagged' => $this->commentService->countFlagged(),
            'hidden' => $this->commentService->countHidden(),
        ]);
    }
}
bash
php artisan vendor:publish --tag=Comments-migrations
bash
php artisan migrate