In Laravel 8.x I am trying to create a blog comment system which allows you to reply to comments. If replying to a comment, the comment is assigned a parent_id which is the id of the comment they are replying to. Currently when I loop the comments with the replies, it will only output a reply 1 loop deep like the example below:
class PostComment extends Model
{
use HasFactory;
public function replies()
{
return $this->hasMany($this, 'parent_id');
}
}
Blade:
@foreach ($comments as $comment)
<p> {{ $comment->user->name }} : {{ $comment->comment }} </p>
@foreach ($comment->replies as $reply)
<p> {{ $reply->user->name }} : {{ $reply->comment }} </p>
@endforeach
@endforeach
Now if I add @foreach ($comment->replies as $reply) 4 times within the comment loop, it will display the replies.. but of course this isn't practical since there can be unlimited responses to a comment. I hope you can understand what I'm trying to get at, I'm awfully bad at explaining things.
Any help is really appreciated :)
create two blade files
comment-list.blade.phpchild-comment-list.blade.phpIn comment-list.blade.php file
@if(count((array)$comments))
@foreach ($comments as $comment)
<p> {{ $comment->user->name }} : {{ $comment->comment }} </p>
@include('child-comment-list',['comments'=>$comment->replies])
@endforeach
@endif
In child-comment-list.blade.php file
@if(count((array)$comments))
@foreach($comments as $comment)
<p> {{ $comment->user->name }} : {{ $comment->comment }} </p>
@if(count((array)$comment->replies))
@include('child-comment-list',['comments'=>$comment->replies])
@endif
@endforeach
So in your current file
@include('comment-list',['comments'=>$comments]);