一般中间件用来过滤用户请求
中间件创建
//php artisan make:middleware 中间件名称
php artisan make:middleware CheckToken
中间分三类:分别是全局中间件、中间件组和指定路由中间件
- 全局中间件
如果你想要定义的中间件在每一个 HTTP 请求时都被执行,只需要将相应的中间件类添加到app/Http/Kernel.php
的数组属性$middleware
中即可:
- 分配中间件到指定路由
$routeMiddleware
中的中间件,可以指定路由
// 在 App\Http\Kernel 类中...
/**
* 应用的路由中间件列表
*
* 这些中间件可以分配给路由组或者单个路由
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'token' => CheckToken::class
];
中间件在 HTTP Kernel 中被定义后,可以使用 middleware 方法将其分配到路由:
//使用
Route::get('/', function () {
//
})->middleware('token');
//多个使用
Route::get('/', function () {
//
})->middleware('token','token2');
$middlewareGroups
的中间件是中间件组
Laravel 自带了开箱即用的 web 和 api 两个中间件组,分别包含可以应用到 Web 和 API 路由的通用中间件:
/**
* 应用的中间件组
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'auth:api',
],
'blog' => [
'token',
]
];
默认情况下,
RouteServiceProvider
自动
将中间件组 web 应用到 routes/web.php
将中间件组 api 应用到 routes/api.php
将中间件组 blog应用到 routes/blog.php
在这里插入代码片
- 在控制器的构造函数中使用中间件
public function __construct(){
//在该控制器中所有方法都会使用`token`中间件
$this.middleware('token')
//只有`index`方法使用`token`中间件
$this.middleware('token').only('index')
//除了`index`和`index2`方法,其他都使用`token`中间件
$this.middleware('token').except('index','index2')
}
- 终端中间件
定义一个终止中间件并添加 terminate 方法到这个中间件(就是请求完毕后,要执行的代码)
<?php
namespace Illuminate\Session\Middleware;
use Closure;
class StartSession
{
public function handle($request, Closure $next)
{
return $next($request);
}
public function terminate($request, $response)
{
// 存储session数据...
}
}