Most Effective way to display comments for a post

Trying to find the best way to display posts from a database with all of their comments. I know there has to be a better way but I can't come up with one.

In my controller, I am sending to a view the following:

$posts = Post::all();

$comments = Comment::all();

return view('layouts.main',compact('posts,comments'));

In my view I am displaying each post with all of its comments below.

@foreach($posts as $post)

    {{ $post->content }}

    @foreach($comments as $comment)

        @if($comment->post->id == $post->id)
            {{ $comment->content }}
        @endif

    @endforeach

@endforeach

Answers


Do you have the comments relationship set up in your posts model?

$posts = Post::with('comments')->all();

return view('layouts.main',compact('posts'));

And then:

@foreach($posts as $post)

    {{ $post->content }}

    @foreach($post->comments as $comment)
            {{ $comment->content }}
    @endforeach

@endforeach

Need Your Help

if parentViewContoller statement

objective-c iphone syntax if-statement parentviewcontroller

I'm writing a program with a UITableView with and add button in the Navigation Bar which leads to an edit page. When you click on an item in the table, a view (rView) is pushed with information

Where put SWFObject in JQuery

jquery document swfobject ready

I have 2 javascripts in my head section.