laravel內置了一個中間件來驗證用戶是否經過認證,如果用戶沒有經過認證,中間件會將用戶重定向到登錄頁面,否則如果用戶經過認證,中間件就會允許請求繼續往前進入下一步操作。
當然,除了認證之外,中間件還可以被用來處理更多其它任務。比如:CORS 中間件可以用於為離開站點的響應添加合適的頭(跨域);日志中間件可以記錄所有進入站點的請求。
Laravel框架自帶了一些中間件,包括認證、CSRF 保護中間件等等。所有的中間件都位於 app/Http/Middleware
目錄。
中間是請求前還是請求后執行取決於中間件本身,以下中間件會在請求處理前執行一些任務
<?php namespace App\Http\Middleware; use Closure; class TestMiddle { public function handle($request, Closure $next) { // 執行動作 if(!$request->session()->has('huser')){ return redirect("login/index"); } return $next($request); } }
而下面這個中間件則會在請求處理后執行其任務:
<?php namespace App\Http\Middleware; use Closure; class TestMiddle { public function handle($request, Closure $next) { $response = $next($request); // 執行動作 if(!$request->session()->has('huser')){ return redirect("login/index"); } return $response; } }
中間件可以自己在編輯器里面新建對應類生成,也可用命令生成
php artisan make:middleware TestMiddle
此時,laravel的app\Http\Middleware\目錄就會多一個TestMiddle.php的中間件文件
此時中間件還不能直接使用,必須把它注冊到我們的laravel中,如下
只需在 app/Http/Kernel.php
類(3個屬性,對應里面加入,我有時用路由的)
'TestMiddle' => \App\Http\Middleware\TestMiddle::class,
分配中間件到路由,下面介紹三種方式
Route::get('/',function(){ return redirect('home/index'); })->middleware('TestMiddle');
Route::group(['middleware' => ['TestMiddle']], function() { Route::controller("db","DataBaseController"); });
Route::controller("home","HomeController",['middleware'=>'TestMiddle']);
http://www.cnblogs.com/fwqblogs/p/6641569.html