什么是Url嵌套资源路由?

问题描述 投票:0回答:2

我可以使用以下代码显示帖子的所有评论

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。

laravel eloquent
2个回答
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的信息


0
投票

您收到错误是因为您没有将帖子ID传递给视图。改为:

return view ('comment.index', compact ('post_id', 'comments'));

然后在视图中使用该变量,例如:

{{ url('posts/' . $post_id . '/comment '/' . $comments->first()->id . ')}}
© www.soinside.com 2019 - 2024. All rights reserved.