介紹
- 中間件提供了一種方便的機制過濾進入應用程序的 HTTP 請求。例如,Laravel 包含一個中間件,驗證您的應用程序的用戶身份驗證。如果用戶未被認證,中間件會將用戶重定向到登錄界面。然而,如果用戶通過身份驗證,中間件將進一步允許請求到應用程序中。
- 當然,除了身份認證以外,還可以編寫另外的中間件來執行各種任務。例如:CORS 中間件可以負責為所有離開應用的響應添加合適的頭部信息;日志中間件可以記錄所有傳入應用的請求。
- Laravel 自帶了一些中間件,包括身份驗證、CSRF 保護等。所有這些中間件都位於
app/Http/Middleware
目錄
定義中間件的命令:
php artisan make:middleware GetCurrentTime
該命令會在 app/Http/Middleware
目錄下創建一個新的GetCurrentTime類,
下面我們來演示一下中間件的簡單使用
編寫一個顯示時間的middleware
編寫完成的中間件必須注冊之后才能使用: 在app\Http\Kernel.php中注冊
1.全局注冊
在Kernel.php的protected $middleware中注冊全局都可以使用
protected $middleware = [ \App\Http\Middleware\GetCurrentTime::class, ];
顯示如下
2.使用路由進行注冊使用 :
在protected $routeMiddleware中注冊路由中間件
protected $routeMiddleware = [
'get_current_time'=>\App\Http\Middleware\GetCurrentTime::class, ];
顯示如下:在路由后面使用鏈式加middleware(‘你定義的路由中間件的名稱’);
結果如下
3. 在控制器中使用
在定義中的控制器中使用的Route代碼
Route::get('demo','TestController@index');
class TestController extends Controller { public function __construct(){
// 排除某些方法 // return $this->middleware(['get_current_time'])->except('index');
return $this->middleware('get_current_time');
}
public function index(){
echo 'a';
}
}
顯示如下