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 AppBlogComments.php
JavaScript
x
public function posts(){
return $this->belongsTo('AppPost');
}
In the AppPost.php
JavaScript
public function BlogComments(){
return $this->hasMany('AppBlogComments');
}
In the BlogCommentsController:
JavaScript
public function getComment($id)
{
$post = Post::find($id);
return $blogcomments->with('posts', $post->blogcomments);
}
In the posts/show.blade.php
JavaScript
@foreach($blogcomments as $blogcomment)
{{$blogcomment->comment}}
@endforeach
Advertisement
Answer
In controller use this
JavaScript
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
JavaScript
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
JavaScript
public function getComment($id)
{
$post = Post::with('blogcomments')->find($id);
return view('posts.show')->with('post', $post);
}
in view
JavaScript
@foreach($post->blogcomments as $blogcomment)
{{$blogcomment->comment}}
@endforeach
Edit: for comment issue
In BlogComments model define
JavaScript
public function user() {
return $this->belongsTo('AppUser');
}
And usage
JavaScript
$post = Post::with('blogcomments.user')->find($id);