Reputation: 17
I am able to display all comments of a post using the below code
public function index($post_id)
{
$comments = post::find($post_id)->comments;
return view ('comment.index', compact ('posts','comments'));
}
and in view index.blade.php
<p> This is comment title {{ $comment->title }}</p>
<p> This is comment name {{ $comment->name }}</p>
but cannot go to the url of each comments ie. show.blade.php gets error with below code when add a "href="
<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>
what will be the url to visit and show posts/1/comments/1 currently I am getting error undefined $post .
Upvotes: 0
Views: 436
Reputation: 1356
You aren't sending a variable named post
to the blade. And looking at the follow piece of code
return view ('comment.index', compact ('posts','comments'));
posts
also looks undefined.
You need to send the post to the view instead of just the comments.
In the controller change:
$comments = post::find($post_id)->comments;
return view ('comment.index', compact ('posts','comments'));
To
$post = post::find($post_id);
return view ('comment.index', compact ('post'));
And then in your view change
<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>
To
{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}
I would also suggest using the route()
function instead of url()
. You can find more about that here
Upvotes: 1
Reputation: 163948
You're getting the error because you're not passing post ID to the view. Do this instead:
return view ('comment.index', compact ('post_id', 'comments'));
Then use the variable in the view, for example:
{{ url('posts/' . $post_id . '/comment '/' . $comments->first()->id . ')}}
Upvotes: 0