Reputation: 61
Hi I am new to Laravel and I and trying to create a relationship bewteen my posts and post comments.
I want to show all comments on a post with the same post_id as the posts id. I think it should look something like this. But I can not get it to work. Any suggestions ?
In the App\BlogComments.php
public function posts(){
return $this->belongsTo('App\Post');
}
In the App\Post.php
public function BlogComments(){
return $this->hasMany('App\BlogComments');
}
In the BlogCommentsController:
public function getComment($id)
{
$post = Post::find($id);
return $blogcomments->with('posts', $post->blogcomments);
}
In the posts/show.blade.php
@foreach($blogcomments as $blogcomment)
{{$blogcomment->comment}}
@endforeach
Upvotes: 2
Views: 6456
Reputation: 8618
In controller use this
public function getComment($id)
{
$post = Post::with('blogcomments')->find($id);
return view('posts.show')->with('blogcomments', $post->blogcomments);
}
Or if only need blogComments that case
public function getComment($id)
{
$blogcomments = BlogComments::where('post_id', $id)->get;
return view('posts.show')->with('blogcomments', $blogcomment);
}
Or you can do it this way
public function getComment($id)
{
$post = Post::with('blogcomments')->find($id);
return view('posts.show')->with('post', $post);
}
in view
@foreach($post->blogcomments as $blogcomment)
{{$blogcomment->comment}}
@endforeach
Edit: for comment issue
In BlogComments model define
public function user() {
return $this->belongsTo('App\User');
}
And usage
$post = Post::with('blogcomments.user')->find($id);
Upvotes: 3