Laravel 中間件提供了一種方便的機制來過濾進入應用的 HTTP 請求
1.使用中件間
在路由器中使用中間件:
Route::get('/', 'IndexController@index')->middleware('auth');
//使用多個中間件
Route::get('/', function () { // })->middleware('first', 'second');
//指定類名
Route::get('admin/profile', function () { // })->middleware(CheckAge::class);
//路由器組使用中間件,需要注冊中間件 在app/http/kernel.php 的$routeMiddleware 屬性中:
Route::group(['middleware' => ['auth']], function () { // });
//中間件組
//Laravel 帶有開箱即用的 web 和 api 中間件,包含了可能應用到 Web UI 和 API 路由的通用中間件:
Route::get('/', function () { // })->middleware('web'); Route::group(['middleware' => ['web']], function () { // });
//注:配置中間件組wed,api, 在 app/http/kernel.php 的 $middlewareGroups 屬性中
在控制器中使用中間件:
public function __construct() { $this->middleware('auth'); $this->middleware('log')->only('index'); $this->middleware('subscribed')->except('store'); }
2.創建中間件
中間件在 app/Http/Middleware 目錄內 新建類
namespace App\Http\Middleware; use Closure; class className { /** * 處理傳入的請求 * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { return $next($request); } }
3.注冊中間件
在 App\Http\Kernel 類內
protected $routeMiddleware = [ 'auth' => \Illuminate\Auth\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, ];
4.中間件的參數
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next,$role)
{
return $next($request);
}
//使用中間件傳參數
Route::get('/', function () { // })->middleware('first:role');
