Search code examples
laravelviewlaravel-blade

How to show comments and replycomments in laravel


I don't know how to show comments and replycomments in my post page. My comments table contains id, sender_id, replyer_id, reply_id, comment_text.

CommentController returns a comment object. In Post.blade.php, how do I write a foreach loop or loops?


Solution

  • Your Controller code must be similar to this:

    public function index() 
    {
        $comments = Comment::with(['sender', 'other-relation'])->get();
        return view('comments.index', compact('comments'));
    }
    

    and your blade code must be similar to this:

    <ul>
    @foreach($comments as $comment)
        <li>{{ $comment->comment_text }}</li>
        @if ($comment->sender) // or other relation 
            <a> {{$comment->sender->name}}<a> // relation name and column name must be fix yourself
        @endif
    @endforeach
    </ul>