Laravel—中间件

中间件

中间件用于对用户的登陆等进行验证,只有满足条件的用户才能进入到页面,否则就跳转到指定页面
Laravel自带的中间件,包括认证,CRSF等,在app/Http/Middleware目录下

中间件的使用分为三个步骤:创建、事例代码、注册、使用

定义中间件

要创建一个新的中间件,在当前目录下使用:

php artisan make:middleware CheckToken

该命令会在app/Http/Middleware目录下创建一个新的中间件类CheckToken

<?php

namespace App\Http\Middleware;

use Closure;

class CheckToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request);
    }
}

注册中间件

中间件分为三类:全局中间件、中间件组、指定路由中间件

全局中间件

如果希望定义的中间件在每一个HTTP请求时都被执行,将相应的中间件类添加到app/HTTP/Kernel.php的数组属性$middleware

/**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,

        //只需要在此处加入相应的类
        \App\Http\Middleware\CheckToken::class,
    ];

指定路由中间件

把中间件分配到指定的路由中,首先在app/Http/Kernel.php文件中为该中间件分配一个key(中间件名),在$routeMiddleware属性中添加

/**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\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,
        //在该位置添加自己定义的中间件
        'token' => \App\Http\Middleware\CheckToken::class,
    ];

注册完,可以使用middleware方法将其分配到路由

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

//分配多个中间件到路由
Route::get('/',function(){
    //
})->middleware('token','auth');

中间件组

通过一个键名的方式将相关的中间件分到一个组里,可以更方便的将其分配到路由,只需将相应的组加到$MiddlewareGroups属性中

/**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],

        //在这里添加相应的中间件组
        'blog' => [
            \App\Http\Middleware\CheckToken::class,
        ],
    ];

中间件参数

中间件默认只有$request,$next两个参数,可以自己定义需要的参数
中间件参数在定义路由时通过分隔中间件名和参数名,多个参数用逗号隔开

Route::put('post/{id}',function($id){
    //
})->middleware('role:editor');