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:
Current example of the problem:
User1: Random post 1..> User2: This text is a response to User1 for post 1
User6: Random post 2..
User7: Random post 3..
What I am trying to achieve:
User1: Random post 1..> User2: This text is a response to User1 for post 1
>> User3: This text is a response to User2 for post 1
>>> User4: This text is a response to User3 for post 1
>>> User5: This text is a response to User3 for post 1
User6: Random post 2..
User7: Random post 3..
My current code
Model: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 :)