我可以使用以下代码
显示帖子的所有评论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>
但不能去每个评论的网址即。添加&#34; href =&#34;
时,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目前我收到错误未定义$ post。
答案 0 :(得分:1)
您没有向刀片发送名为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
答案 1 :(得分:0)
您收到错误是因为您未将帖子ID传递给视图。这样做:
return view ('comment.index', compact ('post_id', 'comments'));
然后在视图中使用变量,例如:
{{ url('posts/' . $post_id . '/comment '/' . $comments->first()->id . ')}}