0
votes

I have post table and comments table. I want to get all posts with its comments and the following returns just post which has comments:

Post::with('comments') 

UPDATE

for example

post_table

id post


1 post1

2 post2

comment table

id post_id comment


1 1 sapmle_comment

Post::with('comments') returns only that posts, which have comments, it returns only first post, becouse second post doesnot have comments, i want to get all post (with or without comments)

2
Then what is the problem, you want Posts with comments!The Alpha
Your question doesn't make any sense. Does Post::with('comments')->get() help?user1669496

2 Answers

0
votes

Your question is not clear enough but to get all the posts with comments you may try this:

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

To get posts only which has comments you may try this:

$posts = Post::has('comments')->get();
0
votes

I'm not too sure what your question is, but I am assuming that it is not returning your comments. If your not able to return posts that do not have comments Sheikh's answer will work for you. If you are not able to retrieve the comments for each post you should make sure your model has defined:

public function comments(){
    return $this->hasMany('Comment');
}

and then make sure your comments model has:

public function post(){
    return $this->belongsTo('Post');
}

If you want to pass this along to your view from the controller you can:

$comments = $post->comments()->orderBy('created_at')->get();
return View::make('view', compact('comments'));

You can loop through each of the comments by:

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