應用場景:檢測登錄,控制器加載數據,傳遞常量php
命令web
//中間件建立命令 php artisan make:middleware Check
<?php namespace App\Http\Middleware; use Closure; class Check { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { echo 'middleware-check'; return $next($request); } }
註冊中間件app\Http\Kernel.phpapi
routeMiddleware註冊app
protected $routeMiddleware = [ /* * 註冊中間件 * Author:MR.zhou * */ 'check' =>Middleware\Check::class, 'goods' =>Middleware\Goods::class, ];
middlewareGroups註冊spa
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', ], // 正常 'dds' =>[ 'goods', 'check' ], /* * 錯誤示範 * 命名重複: check與routeMiddleware下的check命名重複,路由調用的時候會出錯。 * */ 'check' =>[ 'goods', 'check' ]
路由調用code
// 中間件羣組 (b.驗證登錄) Route::group(['middleware' => ['check']], function () { Route::get('/show','IndexController@show'); });
// 能夠調用goods、check兩個中間件 Route::group(['middleware' => ['dds']], function () { Route::get('/show','IndexController@show'); });
Route::get('admin/profile', function () { // })->middleware('auth'); Route::get('/', function () { // })->middleware('first', 'second');
場景一:加載常量中間件
Middleware\Constant.phpblog
<?php namespace App\Http\Middleware; use Closure; class Check { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { define('VERSION','5.8'); return $next($request); } }
Kernel.php註冊常量路由
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, 'check'=>Middleware\Check::class // 註冊常量 ];
路由調用:get
public function index(){ echo VERSION; }
頁面輸出:123456
場景二:檢測登錄;方法跟上面基本同樣
須要掌握的技巧:基本路由加載中間件,加載多箇中間件,羣組中間件