英文:
What is {name:slug} in route parameter in Laravel?
问题
Route::get('/click/{name:slug}', [NameController::class, 'click']);
{name:slug}
是一个路由参数的约束。它指示该参数的值应符合“slug”格式。这是一个内建的约束,用于确保参数是一个简单的URL名称。
我认为“slug”是指简化的URL名称。我希望我理解得对。谢谢。
英文:
Route::get('/click/{name:slug}', [NameController::class, 'click']);
What is {name:slug}? Is it constraint for parameter? How to use it? Is it build-in function?
I think slug is the simple url name. I want to understand it. Thanks.
答案1
得分: 0
了解更多关于 Laravel 模型绑定,特别是自定义绑定键。
这里是关于您的代码的描述:
name
部分是指一个模型,所以在您的代码中应该有一个 Name
模型,:slug
部分是指该模型的属性。这意味着当调用端点/路由 /click/this-is-a-name-slug
时,它将使用该属性查询模型 Name
。
// NameController
public function click(Request $request, Name $name)
{
// Laravel 会自动根据 slug 在 $name 中注入 Name 模型
// 如果没有匹配 slug 的 Name,则控制器会返回 404
}
英文:
Read more about laravel model binding, specifically customizing binding key.
Here's a description for your code:
The name
part refers to a model so in your code there should be a Name
model, the :slug
part refers to the attribute of that model. Meaning when calling the endpoint/route /click/this-is-a-name-slug
it will query the model Name
using that attribute
// NameController
public function click(Request $request, Name $name)
{
// Laravel will inject the Name model in $name automatically based on the slug
// If no Name matched the slug then the controller will return 404
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论