1
votes

I am making a blog and it has some weird issue. I used OneToMany joins between comments and posts model(one post can have many comments) on post model:

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

and on comment model:

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

now the problem i encountered is in show.blade.php which receives data from controller from show() method of controller and returns some data in view about posts.

public function show($id)
{
   $post = Posts::find($id);
   return view('posts.show')->with('post', $post);
}

and from blade template, I am showing comments related with that post acc to postid

<div class="card-body">
     <h5 class="card-title"><strong>test comment:</strong></h5>
     <p class="card-text">{{$post->comments->body}}</p>
</div>

when I display the comment in blade removing body I get this: data from comments table

i tried $post->comments->body but i get error what is wrong with this, the suggestion would be appreciated

1
try with {{$post->comments[0]->body}}Inzamam Idrees
@MaulikShah i have no idea where do i put findOrFail, coz i m directly displaying data from model using blade templateJasbin Karki

1 Answers

8
votes

comments is a collection instance you need to loop through

@foreach($post->comments as $comment)
 <p class="card-text">{{$comment->body}}</p>
@endforeach

Or alternatively with single comment {{$post->comments[key]->body}} Replace key with index like

{{$post->comments[0]->body}}