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!
Please read the documentation of Laravel, it's all there: http://laravel.com/docs/master/eloquent-relationships#querying-relations
You can simply do this though:
// returns all posts which has 1 or more comments
$posts = Post::has('comments')->all();
// if you want more control you can do something like this
$posts = Post::whereHas('comments', function($query) {
$query->where('comment', 'like', 'foo%');
});
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()
Thanks!
And what about Posts without comments?
Once again it's in the documentation
$postsWIthoutComments = Post::has('comments', '=', 0)->get();
@kreitje That was his question... He wanted ONLY posts with comments...
Guys, sorry for my English, but I mean — get all Posts and if post has Comments get all Comments if not get Post only.
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
What if I need all posts with no comments ?
Then you can use Post::all()
All() doesn't exist in 5.6 is i know.
@AlexanderKim You need to use get now
$posts = Post::with('comments')->get();
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 sign in or create an account to participate in this conversation.