Laravel named route for resource controller

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

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")); 

However, when I hit the /faq route and place {{ Route::currentRouteName() }} in my view, it yields faq.faq.index instead of just faq.

回答1:

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.

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:

  1. 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...     ] ]); 
  2. Specify the as option to define a prefix for every route name.

    Route::resource('faq', 'ProductFaqController', [     'as' => 'prefix' ]); 

    This will give you routes such as prefix.faq.index, prefix.faq.store, etc.



回答2:

For answer seekers with Laravel 5.5+ finding this page:

Route::namespace('Admin')->prefix('admin')->name('admin.')->group(function () {      Route::resource('users','UserController');  }); 

These options will result in the following for the Resource:

  • namespace() sets Controller namespace to \Admin\UserController

  • prefix() sets request URi to /admin/users

  • name() sets route name accessor to route('admin.users.index')

In name() the DOT is intended, it is not a typo.

Please let others know if this works in comments for any versions prior to Laravel 5.5, I will update my answer.

Update:

I can confirm that in Laravel 5.3 that the name method is not available. No confirmation yet if supported in 5.4

Taylor accepted my PR to officially document this in 5.5:

https://laravel.com/docs/5.5/routing#route-group-name-prefixes



回答3:

Using Laravel 5.5

Route::resource('gallery', 'GalleryController', ['as' => 'photos']);

important to keep in mind the "resource"

For example, I send something from my project:

Route::resource('admin/posts/tags', 'PostTagController', ['as' => 'posts']); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!