在Laravel中向方法传递两个变量

3

我希望能够通过slug在URL中查找文章,但评论必须通过post_id来查找。

控制器

public function post($slug,$id)
{
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$id)->get();
    return view('content.post',compact('post','comments'));
}

路由

Route::get('post/{slug}', 'PagesController@post')->name('post.show');

这个 $id 不等于 $post 的 id 吗? - V-K
这个回答解决了你的问题吗?如何在Laravel中使用路由变量? - loic.lopez
4个回答

2
Route::get('post/{slug}', 'PagesController@post')->name('post.show');

public function post($slug)
{
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$post->id)->get();
    return view('content.post',compact('post','comments'));
}

2
此答案未处理错误。如果提供的 slug 未找到帖子实体,则会收到通知和方法调用错误,这些错误都未被处理。 - Repox
只需将 $post = Post::where('slug',$slug)->first() or abort(404); 更改为处理错误(未找到)。 - Wahyu Kristianto
1
@WahyuKristianto 或者使用适当的模型绑定,这将在不需要额外代码到控制器的情况下处理此问题。 - Repox

0

请看这里:

$post中获取post_id

public function post($slug){
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$post->id)->get();
    ...
}

@HamadEssa,你不需要在URL中显示$id。请查看更新后的答案。 - Qumber

0
在web.php文件中:
Route::get('post/{slug}', 'PagesController@post')->name('post.show');

在控制器中:

public function post($slug)
{
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$post->id)->get(); //use founded_post_id to find it's comments
    return view('content.post',compact('post','comments'));
}

我编辑了我的回答,你可以通过“slug”访问到你的$post,然后像我的回答一样使用$post->id来访问它的评论,在这种方式中,你的ID不会显示在URL中。 - Reza sh

0

您可以使用路由模型绑定来确保路由根据提供的键找到您的模型。

您的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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接