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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.