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..
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With