Laravel 中间件提供了一种方便的机制来过滤进入应用的 HTTP 请求
1.使用中件间
在路由器中使用中间件:
Route::get(‘/‘, ‘[email protected]‘)->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.中间件的参数
时间: 2024-11-06 00:42:29