路由群组

最后更新于:2022-04-01 15:03:35

Sometimes many of your routes will share common requirements such as URL segments, middleware, namespaces, etc. Instead of specifying each of these options on every route individually, you may use a route group to apply attributes to many routes. Shared attributes are specified in an array format as the first parameter to the Route::group method. ## Middleware Middleware is applied to all routes within the group by defining the list of middleware with the middleware parameter on the group attribute array. Middleware will be executed in the order you define this array: ~~~ Route::group(['middleware' => 'foo|bar'], function() { Route::get('/', function() { // Has Foo And Bar Middleware }); Route::get('user/profile', function() { // Has Foo And Bar Middleware }); }); ~~~ ## Namespaces 您一样可以在 group 属性数组中使用 namespace 参数,指定在这群组中控制器的命名空间: ~~~ Route::group(['namespace' => 'Admin'], function() { // Controllers Within The "App\Http\Controllers\Admin" Namespace Route::group(['namespace' => 'User'], function() { // Controllers Within The "App\Http\Controllers\Admin\User" Namespace }); }); ~~~ > 注意: 在默认情况下,RouteServiceProvider 包含内置您命名空间群组的 routes.php 文件,让您不须使用完整的 App\Http\Controllers 命名空间前缀就可以注册控制器路由。 ## 子域名路由 Laravel 路由一样可以处理通配符的子域名,并且从域名中传递您的通配符参数: 注册子域名路由 ~~~ Route::group(['domain' => '{account}.myapp.com'], function() { Route::get('user/{id}', function($account, $id) { // }); }); ~~~ ## 路由前缀 群组路由可以通过群组的描述数组中使用 prefix 选项,将群组内的路由加上前缀: ~~~ Route::group(['prefix' => 'admin'], function() { Route::get('users', function() { // Matches The "/admin/users" URL }); }); ~~~ You can also utilize the prefix parameter to pass common parameters to your routes: Registering a URL parameter in a route prefix ~~~ Route::group(['prefix' => 'accounts/{account_id}'], function() { Route::get('detail', function($account_id) { // }); }); ~~~ You can even define parameter constraints for the named parameters in your prefix: ~~~ Route::group([ 'prefix' => 'accounts/{account_id}', 'where' => ['account_id' => '[0-9]+'], ], function() { // Define Routes Here }); ~~~
';