您可以使用路由模型绑定来确保路由根据提供的键找到您的模型。
您的Post
模型将需要添加以下方法:
public function getRouteKeyName()
{
return 'slug';
}
然后,在您的路由中,您可以直接引用模型,绑定将自动发生:
public function post(App\Post $post)
{
$comments = Comment::where('post_id',$post->id)->get();
return view('content.post',compact('post','comments'));
}
这使您能够使用以下路由:
Route::get('post/{post}', 'PagesController@post')->name('post.show');
现在,为了方便您参考评论,将它们作为与您的Post
模型相关联的关系添加:
public function comments()
{
return $this->hasMany(Comment::class);
}
还有你的评论
模型:
public function post()
{
return $this->belongsTo(Post::class);
}
这将使您的控制器方法更加简短:
public function post(App\Post $post)
{
return view('content.post',compact('post'));
}
在你的 Blade 视图中,改为执行以下操作:
@foreach($post->comments as $comment)
From: {{ $comment->name }} blah blha
@endforeach
$id
不等于$post
的 id 吗? - V-K