Laravel 中间件:路由中间件 1 个改进

问题

我不想注册一个全局中间件,可以只对某个路由注册中间件么?

回答

除了全局中间件,我们也可以针对某个路由注册中间件,具体做法如下:

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

// 在 App\Http\Kernel 类中...

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,

    'my' => \App\Http\Middleware\MyMiddleware::class,
];

我们将 MyMiddleware 注册为路由中间件,并为其指派了一个键名 my。注册好后,我们就可以通过 middleware 方法为路由分配中间件:

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

也可以为路由分配多个中间件:

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

分配中间件时,还可以传递完整的类名:

use App\Http\Middleware\MyMiddleware;

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

参考

本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!