Laravel:资源控制器将参数从 ID 更改为 Slug [英] Laravel: Resource Controller change parameter from ID to Slug

查看:108
本文介绍了Laravel:资源控制器将参数从 ID 更改为 Slug的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Laravel 应用程序中,我使用了普通路由,例如 GET、POST、PUT 以及所有带有各种控制器的路由.但是随着应用程序的进展,routes/api.php 文件变得非常庞大.因此,我正在使用资源控制器"语法对其进行更改,以实现更简洁和精简的代码.

In my Laravel application I was using the normal routes, such as GET, POST, PUT and all with the various controllers. But as the application progresses, the routes/api.php file is turning out quite bulky. So, I am changing it with the "Resource Controller" syntax, for cleaner and reduced code.

但是,之前我能够使用 url 中的token"或slug"参数来获取数据,例如:show/{token} &show($token)show/{slug} &show($slug),但现在每当我尝试这些或任何其他参数时,我都会收到 404 not found 错误.因此,我只使用默认的id"参数.

However, earlier I was able to use the "token" or "slug" parameters in the url to fetch the data, for example: show/{token} & show($token) or show/{slug} & show($slug), but now whenever I try these or any other parameter I get 404 not found error. Therefore I am stuck with the default "id" parameter only.

之前:

Route::get('/categories', 'CategoryController@index');
Route::get('/categories/{token}', 'CategoryController@show');

现在:

Route::resource('/categories', 'CategoryController');

有什么办法可以将默认的id"参数更改为任何其他..?

Is there any way to change the default "id" parameter to any other ..?

推荐答案

对于资源路由,路由参数是资源名称,第一个参数,单数形式.

For Resource Routing the route parameter is the resource name, first argument, in singular form.

Route::resource('categories', 'CategoryController');

会给你一个category的路由参数.您可以通过运行 php artisan route:list 并查看定义的路由来查看这一点.

Will give you a route parameter of category. You can see this by running php artisan route:list and looking at the routes that are defined.

如果您想为资源使用不同的参数名称,您也可以通过覆盖参数来实现:

If you want to use a different parameter name for a resource you can also do that by overriding the parameter:

Route::resource('categories', 'CategoryController')->parameters([
    'categories' => 'something',
]);

现在使用的路由参数将是something.

Now the route parameter used would be something.

这仅与路由参数名称有关,与如何解析任何绑定无关,除非您有专门为参数名称定义的显式路由模型绑定.

This only has to do with the route parameter name, it has nothing to do with how any binding would be resolved, unless you had an Explicit Route Model Binding defined specifically for a parameter name.

如果您使用隐式路由模型绑定,您将通过 getRouteKeyName 方法在模型本身上定义用于绑定的字段.[在 Laravel 的下一版本中,您将能够定义路由定义本身中使用的字段.]

If you are using Implicit Route Model Bindings you would define on your Model itself what field is used for the binding via the getRouteKeyName method. [In the next version of Laravel you will be able to define the field used in the route definition itself.]

Laravel 6.x 文档 - 控制器 - 资源控制器- 命名资源参数

Laravel 6.x 文档 - 路由 - 模型绑定 - 隐式路由模型绑定 getRouteKeyName

这篇关于Laravel:资源控制器将参数从 ID 更改为 Slug的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆