路由群組

2018-02-24 15:51 更新

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 屬性數(shù)組中使用 namespace 參數(shù),指定在這群組中控制器的命名空間:

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 包含內(nèi)置您命名空間群組的 routes.php 文件,讓您不須使用完整的 App\Http\Controllers 命名空間前綴就可以注冊控制器路由。

子域名路由

Laravel 路由一樣可以處理通配符的子域名,并且從域名中傳遞您的通配符參數(shù):
注冊子域名路由

Route::group(['domain' => '{account}.myapp.com'], function()
{

    Route::get('user/{id}', function($account, $id)
    {
        //
    });

});

路由前綴

群組路由可以通過群組的描述數(shù)組中使用 prefix 選項,將群組內(nèi)的路由加上前綴:

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
});
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號