问题描述
使用Laravel 4.2,是否可以为资源控制器路由分配名称?我的路线定义如下:
Using Laravel 4.2, is it possible to assign a name to a resource controller route? My route is defined as follows:
Route::resource('faq', 'ProductFaqController');
我尝试将名称选项添加到这样的路由中:
I tried adding a name option to the route like this:
Route::resource('faq', 'ProductFaqController', array("as"=>"faq"));
但是,当我按/faq路线并将{{ Route::currentRouteName() }}
放置在视图中时,它会显示faq.faq.index
而不是faq
.
However, when I hit the /faq route and place {{ Route::currentRouteName() }}
in my view, it yields faq.faq.index
instead of just faq
.
推荐答案
使用资源控制器路由时,它会自动为其创建的每个路由生成名称. Route::resource()
基本上是一种帮助程序方法,它可以为您生成单独的路由,而不需要您手动定义每个路由.
When you use a resource controller route, it automatically generates names for each individual route that it creates. Route::resource()
is basically a helper method that then generates individual routes for you, rather than you needing to define each route manually.
您可以查看通过在终端/控制台中输入Laravel 4中的php artisan routes
或Laravel 5中的php artisan route:list
生成的路由名称.您还可以在资源控制器文档页面( Laravel 4.x | Laravel 5.x ).
You can view the route names generated by typing php artisan routes
in Laravel 4 or php artisan route:list
in Laravel 5 into your terminal/console. You can also see the types of route names generated on the resource controller docs page (Laravel 4.x | Laravel 5.x).
有两种方法可以修改资源控制器生成的路由名称:
There are two ways you can modify the route names generated by a resource controller:
-
为第三个参数
$options
数组的一部分提供一个names
数组,每个键是资源控制器方法(索引,存储,编辑等),而值是您想要的名称给出路线.
Supply a
names
array as part of the third parameter$options
array, with each key being the resource controller method (index, store, edit, etc.), and the value being the name you want to give the route.
Route::resource('faq', 'ProductFaqController', [
'names' => [
'index' => 'faq',
'store' => 'faq.new',
// etc...
]
]);
指定as
选项为每个路由名称定义一个前缀.
Specify the as
option to define a prefix for every route name.
Route::resource('faq', 'ProductFaqController', [
'as' => 'prefix'
]);
这将为您提供诸如prefix.faq.index
,prefix.faq.store
等的路线.
This will give you routes such as prefix.faq.index
, prefix.faq.store
, etc.
这篇关于Laravel为资源控制器命名路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!