laravel中间件

时间:2020-05-30
本文章向大家介绍laravel中间件,主要包括laravel中间件使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.控制器方法中自定义

$this->middleware(function ($request, $next) {
    return $next($request);
});

 

2.控制器方法中调用

注册中间件
lumen:
$app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
    'UserCheck' => App\Http\Middleware\UserCheck::class,
]);

laravel:app\Http\Kernel.php

 protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'SensitiveFilter' => \App\Http\Middleware\UserCheck::class
    ];

    /**
     * The priority-sorted list of middleware.
     *
     * This forces non-global middleware to always be in the given order.
     *
     * @var array
     */
    protected $middlewarePriority = [
        \App\Http\Middleware\Authenticate::class,
        \App\Http\Middleware\UserCheck::class,
    ];

 

$this->middleware('UserCheck');

UserCheck中间件:app\Http\Middleware\UserCheck.php

<?php
namespace App\Http\Middleware;

use Closure;

class UserCheck
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $path      = $request->route();
        $actionArr = getAction($path);
        $staffInfo = getLoginInfo();

        if(empty($staffInfo['info']))
        {
            return response()->json(['code' => $actionArr['action'].':fail','errMsg' => '用户可能已经被删除']);
        }

        if(!empty($staffInfo['info']['tmp']))
        {
            //锁定状态的用户信息不可以提交修改
            $lock = $staffInfo['info']['tmp']['lock'];
            if($request->isMethod('post'))
            {
                if($lock == 1)
                {
                    return response()->json(['code' => $actionArr['action'].':fail','errMsg' => '用户信息已经锁定,请等待人事审核']);
                }
            }
        }

        $request->attributes->add(['staffInfo'=>$staffInfo]);

        return $next($request);
    }
}

 

$flag 上一页 下一页