Laravel中间件

前置 & 后置中间件

中间件是在请求之前或者之后执行,取决于中间件的本身。例如,下面的中间件将在应用处理请求 之前 执行某些任务:

 

<?php

namespace App\Http\Middleware;

use Closure;

class BeforeMiddleware

{

    public function handle($request, Closure $next)

    {

        // Perform action

        return $next($request);

    }

}

 

然而,这个中间件是在应用请求 之后执行某些任务:

<?php



namespace App\Http\Middleware;



use Closure;



class AfterMiddleware

{

    public function handle($request, Closure $next)

    {

        $response = $next($request);



        // Perform action



        return $response;

    }

}

 

全局中间件

如果你希望中间件在应用处理每个 HTTP 请求期间运行。只需要在 app/Http/Kernel.php 中的 $middleware 属性中列出这个中间件

protected $middleware = [

        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,

        \App\Http\Middleware\LogMiddleware::class,

        \App\Http\Middleware\EnableCrossRequestMiddleware::class

    ];

为路由分配中间件

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

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 核心的 $middlewareGroups 属性。

 

Laravel 内置了开箱即用的 web 和 api 中间件组,其中包含你可能希望应用于 Web UI 和 API 路由的常用中间件:

    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\ApiMiddleware::class,

            \App\Http\Middleware\VerifyCsrfToken::class,

        ],



        'api' => [

            'throttle:60,1',

        ],

    ];