PHP code example of fiachehr / laravel-comments-pro

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

    

fiachehr / laravel-comments-pro example snippets




namespace App\Models;

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

// Works with any model - Post, Article, Product, etc.
class Post extends Model
{
    use HasComments;
    
    // Your model code...
}

// Example with different models
class Article extends Model
{
    use HasComments;
}

class Product extends Model
{
    use HasComments;
}

use Fiachehr\Comments\Facades\Comments;

// Works with any model that uses HasComments trait
$post = Post::find(1);
$article = Article::find(1);
$product = Product::find(1);

// For authenticated users
$comment = Comments::create([
    'body' => 'This is a great post!',
], $post);

// For guest users
$comment = Comments::create([
    'body' => 'Nice article!',
    'guest_name' => 'John Doe',
    'guest_email' => '[email protected]',
], $article);

// Nested comments
$reply = Comments::create([
    'body' => 'Thanks for the comment!',
    'parent_id' => $comment->id,
], $product);

use Fiachehr\Comments\Facades\Comments;

$comment = Comments::approve($comment);

use Fiachehr\Comments\Facades\Reactions;
use Fiachehr\Comments\Enums\ReactionType;

// Like a comment
$reaction = Reactions::toggle($comment, ReactionType::LIKE);

// Dislike a comment
$reaction = Reactions::toggle($comment, ReactionType::DISLIKE);

use Fiachehr\Comments\Facades\Comments;

$comments = $post->comments()->approved()->get();
$tree = Comments::toTree($comments);

// config/comments.php (after publishing)

return [
    'route_prefix' => 'api/comments',
    'middleware' => ['api', 'throttle:60,1'],
    'max_depth' => 5,
    'auto_approve_authenticated' => true,
    'reply_only_to_approved_parent' => true,

    'guests' => [
        'allowed' => true,
        '

use Fiachehr\Comments\Services\CommentsService;
use Fiachehr\Comments\Services\ReactionService;

// Direct service usage
$commentsService = app(CommentsService::class);
$comment = $commentsService->createComment($data, $post);

$reactionService = app(ReactionService::class);
$reaction = $reactionService->toggleReaction($comment, ReactionType::LIKE);

use Fiachehr\Comments\Events\CommentCreated;
use Fiachehr\Comments\Events\CommentApproved;
use Fiachehr\Comments\Events\ReactionToggled;

// Listen to events
Event::listen(CommentCreated::class, function (CommentCreated $event) {
    // Handle new comment
    $comment = $event->comment;
    // Send notification, log activity, etc.
});

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

// Get comments with reactions
$commentsWithReactions = $post->comments()->withReactions()->get();

// Get popular comments (service)
$popularComments = app(ReactionService::class)->getPopularComments(10, '7 days');

// Or via facade
$popularComments = Reactions::getPopular(10, '7 days');

use Fiachehr\Comments\Facades\Reactions;

// Bulk reactions
$results = Reactions::bulkToggle([1, 2, 3], ReactionType::LIKE);

// Get reaction statistics
$stats = Reactions::getStats($comment);
// Returns: ['likes' => 5, 'dislikes' => 2, 'total' => 7]



namespace App\Http\Controllers;

use App\Http\Requests\StoreCommentRequest;
use Fiachehr\Comments\Services\CommentsService;
use Fiachehr\Comments\Services\ReactionService;
use Fiachehr\Comments\Enums\ReactionType;
use Illuminate\Database\Eloquent\Model;

class CommentController extends Controller
{
    public function __construct(
        private CommentsService $commentsService,
        private ReactionService $reactionService
    ) {}

    // Works with any model that uses HasComments trait
    public function store(StoreCommentRequest $request, Model $commentable)
    {
        $comment = $this->commentsService->createComment($request->validated(), $commentable);
        
        return response()->json([
            'success' => true,
            'comment' => $comment,
        ]);
    }
    
    public function approve(Comment $comment)
    {
        $approvedComment = $this->commentsService->approveComment($comment);
        
        return response()->json([
            'success' => true,
            'comment' => $approvedComment,
        ]);
    }
    
    public function react(Comment $comment, string $type)
    {
        $reactionType = ReactionType::from($type);
        $reaction = $this->reactionService->toggleReaction($comment, $reactionType);
        
        return response()->json([
            'success' => true,
            'reaction' => $reaction,
        ]);
    }
    
    // Works with any commentable model
    public function tree(Model $commentable)
    {
        $comments = $commentable->comments()->approved()->get();
        $tree = $this->commentsService->toTree($comments);
        
        return response()->json($tree);
    }
}



namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Fiachehr\Comments\Rules\GuestFingerprint;

class StoreCommentRequest extends FormRequest
{
    public function rules()
    {
        return [
            'body' => 'ew GuestFingerprint()],
        ];
    }
}

// Add custom indexes for better performance
Schema::table('comments', function (Blueprint $table) {
    $table->index(['commentable_type', 'commentable_id', 'status']);
    $table->index(['parent_id', 'depth']);
    $table->index(['created_at', 'status']);
});

use Illuminate\Support\Facades\Cache;

// Cache popular comments
$popularComments = Cache::remember('popular_comments', 3600, function () {
    return app(ReactionService::class)->getPopularComments(10);
});

// Cache comment trees
$commentTree = Cache::remember("comments_tree_{$post->id}", 1800, function () use ($post) {
    return app(CommentsService::class)->toTree($post->comments()->approved()->get());
});

// Load comments with relationships
$comments = $post->comments()
    ->with(['user', 'reactions', 'children'])
    ->approved()
    ->get();

   // Make sure to publish factories
   php artisan vendor:publish --provider="Fiachehr\Comments\CommentsServiceProvider" --tag=comments-factories
   

   // Check if events are registered in EventServiceProvider
   protected $listen = [
       CommentCreated::class => [
           // Your listeners
       ],
   ];
   

   // This package only works with Laravel
   // Not compatible with: Symfony, CodeIgniter, etc.
   // Requires: Laravel 10–12 (PHP 8.2+ for Laravel 11/12)
   

// Enable debug logging
Log::info('Comment created', ['comment' => $comment->toArray()]);
Log::info('Reaction toggled', ['reaction' => $reaction->toArray()]);

// Track comment metrics
$stats = [
    'total_comments' => Comment::count(),
    'approved_comments' => Comment::approved()->count(),
    'pending_comments' => Comment::where('status', 'pending')->count(),
    'total_reactions' => Reaction::count(),
    'popular_posts' => app(ReactionService::class)->getPopularComments(5),
];

// Check system health
$health = [
    'database_connection' => DB::connection()->getPdo() !== null,
    'migrations_up_to_date' => !Artisan::call('migrate:status'),
    'config_loaded' => config('comments') !== null,
    'services_registered' => app()->bound(CommentsService::class),
];
bash
php artisan vendor:publish --provider="Fiachehr\Comments\CommentsServiceProvider" --tag=comments-migrations
php artisan migrate
bash
php artisan vendor:publish --provider="Fiachehr\Comments\CommentsServiceProvider" --tag=comments-config
xml
<testsuite name="Comments">
    <directory suffix="Test.php">./vendor/fiachehr/laravel-comments-pro/tests/Unit</directory>
</testsuite>
bash
   # Check PHP version
   php --version
   
   # Check Laravel version
   php artisan --version
   
   # Ensure minimum 
bash
   # Clear cache and re-run migrations
   php artisan cache:clear
   php artisan config:clear
   php artisan migrate:fresh