5
我有認證使用tymon/jwt-auth封裝的JWT用戶中間件:在Controller的構造函數之前在Laravel 5.1上運行中間件?
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);
}
然後,我有一個控制器,我想從中間件向控制器傳遞用戶。
所以,我做的控制器上:
public function __construct()
{
$this->user = \Auth::user();
}
的問題是,$this->user
是null
,但我這樣做對控制器的方法時,它不是空。
所以:
public function __construct()
{
$this->user = \Auth::user();
}
public function index()
{
var_dump($this->user); // null
var_dump(\Auth::user()); // OK, not null
}
所以,問題是__construct
是中間件之前運行。我該如何改變這種情況,還是有另一種解決方案?
更新:我使用dingo/api進行路由,也許這是他們的錯誤?
你不能做到這一點。您已經考慮如何從中間件(而不是控制器)傳遞該用戶。 – num8er
@ num8er即使當我傳遞'$ user'參數時:'$ request-> attributes-> add(compact('user'));'我在控制器上得到相同的結果,因爲構造函數在中間件。 (可能是dingo/api錯誤) – HtmHell
檢查我的回答 – num8er