Saturday, March 17, 2018

How To build Multilevel Nested Comments System in Laravel? - development

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('AppModelPost');
    }

    public function user(){
        return $this->belongsTo('AppModelUser');
    }

    public function replies() {
        return $this->hasMany('AppModelComment', '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 .



from Laravel Questions and Answers https://laravelquestions.com/laravel/how-to-build-multilevel-nested-comments-system-in-laravel/
via Lzo Media

No comments:

Post a Comment