laravel之中间件实例教程

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 方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值