简体   繁体   English

Laravel 更改 URL 名称详细信息

[英]Laravel Change URL name detail

How do I make the post single URL like myweb.com/post-name instead myweb.com/post-id ?如何使帖子单一 URL 像 myweb.com/post-name 而不是 myweb.com/post-id ? its works fine with posts id, but not with post name.它适用于帖子 ID,但不适用于帖子名称。

here my current route.这是我目前的路线。

Route::get('/{id}', [App\http\Controllers\PostController::class, 'show']);

and here my controller.这里是我的控制器。

public function show($id)
{
    $post = post::find($id);
    return view('detail', ['post' => $post]);
}

thank you.谢谢你。

That is because you are using the $id as the identifier to resolve the post object:那是因为您使用$id作为标识符来解析 post 对象:

myweb.com/25

Then:然后:

public function show($id) // $id = 25
{
    $post = post::find($id); // find() search for the PK column, "id" by default

    return view('detail', ['post' => $post]);
}

If you want to resolve the $post by a different field, do this:如果您想通过不同的字段解析$post ,请执行以下操作:

public function show($name)
{
    $post = post::where('name', $name)->first();

    return view('detail', ['post' => $post]);
}

This should work for a route like this:这应该适用于这样的路线:

myweb.com/a-cool-post-name

As a side note, you could resolve the model automatically makin use of Route Model Binding .作为旁注,您可以使用Route Model Binding自动解析模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM