Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel eloquent nested comment and replies

Few days ago, I saw a website where users can comment on a post. Other users can reply on that. and a replay can have replies like the example screenshot below.. enter image description here

So I thought to give it a try but somehow couldnt figure it out. here is my database set up

Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id');
            $table->unsignedInteger('post_id');
            $table->unsignedInteger('reply_id')->default(0);
            $table->text('body');
            $table->timestamps();
        });

relationships in model

class Comment extends Model
{
    protected $fillable = [
        'user_id',
        'post_id',
        'reply_id',
        'body'
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function post()
    {
        return $this->belongsTo(Post::class);
    }

    public function replies()
    {
        return $this->hasMany(Comment::class,'reply_id','id');
    }

in controller

$comments = Comment::with('replies')->where('reply_id','=',0)->get(['id','reply_id','body']);
   return response($comments);

this perfectly returns the comment and replies. But if there is a reply of reply, it doesnt show up. How can I do that? Need suggestion.

like image 527
Noob Coder Avatar asked Dec 10 '22 13:12

Noob Coder


1 Answers

Swap reply_id with a nullable() parent_id. So basically you want to know if a comment has a parent.

Then in Comment model, add a self relationship to take all comments whose parent_id match.

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

In your view you can have nested loops for each comments and its replies

@foreach($comments as $comment) 
   {{ $comment->content }}

   @if ( $comment->replies )
       @foreach($comment->replies as $rep1)
           {{ $rep1->content }}
           ...
       @endforeach
   @endif
@endforeach
like image 129
EddyTheDove Avatar answered Jan 11 '23 23:01

EddyTheDove