阅读(2538) (7)

Laravel 8 为路由分配中间件

2021-06-24 09:21:02 更新

假设你想为指定的路由分配中间件 , 首先应该在 app/Http/Kernel.php 文件内为该中间件分配一个键。默认情况下,该类中的 $routeMiddleware 属性下包含了 Laravel 内置的中间件。若要加入自定义的中间件,只需把它附加到列表后并为其分配一个自定义键。例如:

// Within App\Http\Kernel Class...

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];

在 HTTP 内核中定义了中间件后,您可以使用 middleware 方法将中间件分配给路由:

Route::get('admin/profile', function () {
    //
})->middleware('auth'); 

您还可以将多个中间件分配给路由:

Route::get('/', function () {
    //
})->middleware('first', 'second'); 

分配中间件时,您还可以传递完全限定的类名:

use App\Http\Middleware\CheckAge;

Route::get('admin/profile', function () {
    //
})->middleware(CheckAge::class); 

将中间件分配给一组路由时,有时可能需要阻止将中间件应用于该组中的单个路由。 您可以使用 withoutMiddleware 方法完成此操作:

use App\Http\Middleware\CheckAge;

Route::middleware([CheckAge::class])->group(function () {
    Route::get('/', function () {
        //
    });

    Route::get('admin/profile', function () {
        //
    })->withoutMiddleware([CheckAge::class]);
});

withoutMiddleware 方法只能删除路由中间件,不适用于 全局中间件