在Laravel 5.1上运行控制器构造函数之前的中间件?

HTM*_*ell 5 php laravel laravel-middleware dingo-api laravel-5.1

我有一个使用tymon/jwt-auth软件包验证JWT用户的中间件:

public function handle($request, \Closure $next)
{
    if (! $token = $this->auth->setRequest($request)->getToken()) {
        return $this->respond('tymon.jwt.absent', 'token_not_provided', 400);
    }

    try {
        $user = $this->auth->authenticate($token);
    } catch (TokenExpiredException $e) {
        return $this->respond('tymon.jwt.expired', 'token_expired', $e->getStatusCode(), [$e]);
    } catch (JWTException $e) {
        return $this->respond('tymon.jwt.invalid', 'token_invalid', $e->getStatusCode(), [$e]);
    }

    if (! $user) {
        return $this->respond('tymon.jwt.user_not_found', 'user_not_found', 404);
    }

    $this->events->fire('tymon.jwt.valid', $user);

    return $next($request);
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个控制器,我想将用户从中间件传递给控制器​​.

所以我在控制器上做了:

public function __construct()
{
    $this->user = \Auth::user();
}
Run Code Online (Sandbox Code Playgroud)

问题是,$this->usernull的,但我做这个控制器的方法时,它不是空.

所以:

public function __construct()
{
    $this->user = \Auth::user();
}

public function index()
{
    var_dump($this->user); // null
    var_dump(\Auth::user()); // OK, not null
}
Run Code Online (Sandbox Code Playgroud)

所以问题是__construct在中间件之前运行.我该如何改变,或者你有其他解决方案?

更新:我正在使用dingo/api进行路由,也许这是他们身边的错误?

num*_*8er 0

1) 从内核$middleware数组中删除中间件

2)将您的中间件放入$routeMiddleware具有自定义名称的数组中jwt.auth

protected $routeMiddleware = [
    // ...
    'jwt.auth' => 'App\Http\Middleware\YourAuthMiddleware'
];
Run Code Online (Sandbox Code Playgroud)

2)在needlecontroller的父目录下创建BaseController,功能:

public function __construct() {
    $this->middleware('jwt.auth');
}
Run Code Online (Sandbox Code Playgroud)

3)从BaseController扩展针控制器

4)使needle控制器的__construct函数看起来像这样:

public function __construct() {
    parent::__construct();
    $this->user = \Auth::user();
}
Run Code Online (Sandbox Code Playgroud)