'How To build Multilevel Nested Comments System in Laravel?

Im working on Laravel Blog App , in which I need multilevel nested comment below the blog post as displayed in photo.

enter image description here

Below is the Database migration schema for comments table

 Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('parent_id')->unsigned();
            $table->text('comment');
            $table->integer('post_id')->unsigned();
            $table->integer('user_id')->unsigned();
            $table->timestamps();
        });

Below is the Comment Model Class:

class Comment extends Model
{
    protected $table='comments';
    public $primaryKey='id';
    protected $fillable = [
        'parent_id',
        'comment',
        'post_id',
        'user_id'
    ];


    public function post(){
        return $this->belongsTo('App\Model\Post');
    }

    public function user(){
        return $this->belongsTo('App\Model\User');
    }

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

Here is screenshot of comments table :

enter image description here

Im able to get only 1st level of reply using below code :

public function show($slug)
   {
   $post=Post::where(['slug'=>$slug])->with('user')->first();
    $comments=Comment::where(['post_id'=>$post->id,'parent_id'=>0])->orderBy('created_at','asc')->with('replies')->get();
    return response()->json($comments);
   }

Below is the response of above query :

enter image description here

As you see in reponse , im getting only 2 replies in comment id 7 , but in database comment id 10 to 16 are reply of reply of comment ....that is not displaying ...I want to fetch and display that .

I have searched many question on StackOverflow and Google but not found any useful resource . Please Help me to solve this .



Solution 1:[1]

edit the relationship in the comment model to the following in order to get multilevel replies . For me this wasn't the problem, the problem I faced was how to limit the level of replies and still look for a solution;

return $this->hasMany('App\Model\Comment', 'parent_id')->with('replies');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ibrahem Aljabr