简体   繁体   English

Laravel 5.4 - 如何使用通配符路由?

[英]Laravel 5.4 - How to route with wildcard?

After some playing around and research it seems that Route::when() and Route::filter() are deprecated in Laravel 5+.经过一些玩耍和研究后,似乎Route::when()Route::filter()在 Laravel 5+ 中已被弃用。 I need to be able to route all URIs that begin with members to the same controller.我需要能够将所有以members开头的 URI 路由到同一个控制器。 For example:例如:

Route::get('members/home', 'MembersController');
Route::get('members/view/all', 'MembersController');
Route::get('members/any/possible/route', 'MembersController');

I will not know all the possible routes that begin with members, as they will be stored in my database.我不会知道所有以成员开头的可能路线,因为它们将存储在我的数据库中。 Is there a wildcard equivalent to what Laravel 4.2 had that I can use in 5.4?我可以在 5.4 中使用与 Laravel 4.2 相同的通配符吗?

The idea is to have any routes that begin with certain prefixes to go to its specified controller, then the controller will compare the entire URI string and retrieve the page that has the matching slug in the db.这个想法是让任何以某些前缀开头的路由都转到其指定的控制器,然后控制器将比较整个 URI 字符串并检索数据库中具有匹配 slug 的页面。

You can do this using a route parameter that allows any value.您可以使用允许任何值的路由参数来执行此操作。 Eg (.*) .例如(.*) You'll then need to handle all of the requests from a single controller action.然后,您需要处理来自单个控制器操作的所有请求。

Route::get('members/{action}', 'MemberController@all')->where('action', '(.*)');

To take this further, if you don't know that your requests will all be GET requests, you could use the :any method type.更进一步,如果您不知道您的请求都是GET请求,您可以使用:any方法类型。

Route::any('members/{action}', 'MemberController@all')->where('action', '(.*));
Route::get('/members/{section}', 'MembersController@index' )
       ->where(['section' => '.*']);

Or better yet you can use a group route.或者更好的是,您可以使用组路由。 It's faster and optimizes your app.它更快并优化您的应用程序。

Route::prefix('members')->group(function () {
    Route::get('{section}', 'MembersController@index' )
        ->where(['section' => '.*']);
});

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

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