我可以使用以下代码显示帖子的所有评论
public function index($post_id)
{
$comments = post::find($post_id)->comments;
return view ('comment.index', compact ('posts','comments'));
}
并在视图中index.blade.php
<p> This is comment title {{ $comment->title }}</p>
<p> This is comment name {{ $comment->name }}</p>
但不能去每个评论的网址即。添加“href =”时,show.blade.php会出现以下代码错误
<a href="{{ url('posts/' . $post->id . '/comment '/' . $comment->id . ')}}" >{{ $comment->name }}</a>
<p> This is comment title {{ $comment->title }}</p>
<p> This is comment name {{ $comment->name }}</p>
什么是访问的网址和显示帖子/ 1 /评论/ 1目前我收到错误undefined $ post。
您没有向刀片发送名为post
的变量。并查看下面的代码
return view ('comment.index', compact ('posts','comments'));
posts
看起来也未定义。
您需要将帖子发送到视图而不仅仅是评论。
在控制器中更改:
$comments = post::find($post_id)->comments;
return view ('comment.index', compact ('posts','comments'));
至
$post = post::find($post_id);
return view ('comment.index', compact ('post'));
然后在你看来改变
<a href="{{ url('posts/' . $post->id . '/comment '/' . $comment->id . ')}}" >{{ $comment->name }}</a>
<p> This is comment title {{ $comment->title }}</p>
<p> This is comment name {{ $comment->name }}</p>
至
{foreach $post->comments as $comment}
<a href="{{ url('posts/' . $post->id . '/comment '/' . $comment->id . ')}}">{{ $comment->name }}</a>
<p> This is comment title {{ $comment->title }}</p>
<p> This is comment name {{ $comment->name }}</p>
{/foreach}
我还建议使用route()
函数而不是url()
。你可以找到更多关于那个here的信息
您收到错误是因为您没有将帖子ID传递给视图。改为:
return view ('comment.index', compact ('post_id', 'comments'));
然后在视图中使用该变量,例如:
{{ url('posts/' . $post_id . '/comment '/' . $comments->first()->id . ')}}