Slon's avatar
Level 2

Get all posts with all comments

Hello,

for example:

$post = Post::find(1)->comments;

it's work and return one post and all it comments. How can I get ALL Posts with Comments?

Something like this:

$post = Post::all()->comments;

Thanks!

0 likes
15 replies
kreitje's avatar

This one will get all posts and comments. What bobbybouwmann posted, will get all posts that have comments while leaving posts with no comments out.

$post = Post::with('comments')->get()
2 likes
Slon's avatar
Level 2

Thanks!

And what about Posts without comments?

bobbybouwmann's avatar

Once again it's in the documentation

$postsWIthoutComments = Post::has('comments', '=', 0)->get();
Slon's avatar
Level 2

Guys, sorry for my English, but I mean — get all Posts and if post has Comments get all Comments if not get Post only.

bobbybouwmann's avatar
Level 88

That's something completely different, well you can do it like this

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

return view('myview', compact('posts'));

And then you can do this in your view

@foreach($posts as $post)

    // Display post information

    @if (count($post->comments))
        @foreach($post->comments as $comment)
            // Display comment information
        @endforeach
    @else 
        No comments Found
    @endif  

@endforeach
3 likes
rohitcp's avatar

What if I need all posts with no comments ?

Ctrl+'s avatar

What if I only want the comments from those posts? lets say Post::where('created_at','>','19'). How do I get only the comments?

Please or to participate in this conversation.