1、中间件简介
laravel中可以把http中间件看做装饰器,在请求到达最终动作之前对请求进行过滤和处理,中间件类默认放在 app\http\middleware 文件夹下
比如用户认证,日志,维护模式,session,csrf防止攻击等。
2、中间件创建及使用
php artisan make:middleware MiddlewareNameMiddleware
自定义中间件类只需要定义一个 handle 方法即可,我们将主要业务逻辑写在该方法中
a.如果想在请求处理之前执行中间件业务逻辑,则在 $next 闭包执行前,执行业务逻辑
public function handle($request,Closure $next){
//执行你的业务逻辑
return $next($request);
}
b.如果想在请求处理之后执行中间件业务逻辑,则 $next 闭包执行以后,再执行业务逻辑
public function handle($request,Closure $next){
$response = $next($request);
//执行业务逻辑
return $response;
}
c.中间件参数
public function handel($request,Closure $next,$gender){
if($request->input('age') >= 18 && $gender === $request->input('gender') ){
return $next($request);
}else{
return redirect()->route('refuse');
}
}
对应的路由配置如下
Route::group(['middleware'=>'test:male'],function(){
Route::get('sensitive/info',function(){
//執行中間件
});
});
Route::get('age/refuse',function(){
return '僅限18以上的男性訪問';
});
d.定义可终止的中间件
//TODO terminate 方法
laravel之中间件实例教程
最新推荐文章于 2021-12-19 21:19:36 发布