如何使帖子的单个URL类似于myweb.com/post-name而不是myweb.com/post-id?它可以与帖子ID配合使用,但不能与帖子名称配合使用。
这是我当前的路线。
Route::get('/{id}', [App\http\Controllers\PostController::class, 'show']);
还有我的控制器。
public function show($id)
{
$post = post::find($id);
return view('detail', ['post' => $post]);
}
谢谢。
答案 0 :(得分:0)
那是因为您使用$id
作为标识符来解析发布对象:
myweb.com/25
然后:
public function show($id) // $id = 25
{
$post = post::find($id); // find() search for the PK column, "id" by default
return view('detail', ['post' => $post]);
}
如果您想通过其他字段来解析$post
,请执行以下操作:
public function show($name)
{
$post = post::where('name', $name)->first();
return view('detail', ['post' => $post]);
}
这应该适用于这样的路线:
myweb.com/a-cool-post-name
请注意,您可以自动使用Route Model Binding来解析模型。