laravel eloquent nested comment and replies

前端 未结 1 1591
执笔经年
执笔经年 2020-12-18 10:07

Few days ago, I saw a website where users can comment on a post. Other users can reply on that. and a replay can have replies like the example screenshot below..

So

相关标签:
1条回答
  • 2020-12-18 10:35

    Swap reply_id with a nullable() parent_id. So basically you want to know if a comment has a parent.

    Then in Comment model, add a self relationship to take all comments whose parent_id match.

    public function replies() {
        return $this->hasMany('App\Comment', 'parent_id');
    }
    

    In your view you can have nested loops for each comments and its replies

    @foreach($comments as $comment) 
       {{ $comment->content }}
    
       @if ( $comment->replies )
           @foreach($comment->replies as $rep1)
               {{ $rep1->content }}
               ...
           @endforeach
       @endif
    @endforeach
    
    0 讨论(0)
提交回复
热议问题