Make self relations in Comment model
Comment.php
public function parent()
{
return $this->belongsTo(self::class, 'parent_id');
}
public function child()
{
return $this->hasOne(self::class, 'parent_id');
}
going top to bottom in heirarchy
CommentController.php
use Illuminate\Support\Collection;
......
$parent = $this;
$ids= new Collection();
while ($parent->child) { // loop will stop if parent has no child
$ids->push($parent->child->id);
$parent = $parent->child; // make child as parent to continue loop to get child of child
}
$comments = Comment::whereIn('parent_id', $ids)->get()
going bottom to top in heirarchy
CommentController.php
use Illuminate\Support\Collection;
......
$child= $this;
$ids= new Collection();
while ($child->parent) { // loop will stop if parent has no child
$ids->push($child->parent->id);
$child= $child->parent; // make child as parent to continue loop to get child of child
}
$comments = Comment::whereIn('parent_id', $ids)->get()
If you have comment with many replies and replies of replies and you want to get top parent comment and all of his replies so you can do it like this
Comment.php
// This relation will work like loop it will get all replies with replies
//because it call ->with() function on each instance
public function replies()
{
return $this->hasMany(self::class, 'parent_id')->with('replies);
}
CommentController.php
use App\Models\Comment;
.......
return Comment::where('parent_id', null) // This condition get top parent comment
->with('replies')
->get()
And you can call relation on instance to get his replies
return $parentComment->replies;