Skip to content
Advertisement

Show post comments with relationship – Laravel

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

   public function posts(){
       return $this->belongsTo('AppPost');
   }

In the AppPost.php

public function BlogComments(){
    return $this->hasMany('AppBlogComments');
}

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

Advertisement

Answer

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('AppUser');
}

And usage

$post = Post::with('blogcomments.user')->find($id);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement