gpt4 book ai didi

php - laravel 5.4:无法在 __construct 方法中访问 Auth::user()

转载 作者:可可西里 更新时间:2023-11-01 12:30:40 24 4
gpt4 key购买 nike

在以前版本的 Laravel 中,在我需要访问已登录用户的所有方法中的 Controller 中,我曾经做过这样的事情:

class DashboardController extends Controller
{
private $user ;
function __construct(Request $request)
{
$this->middleware('auth');
$this->user = \Auth::user();
}

function func_1(){
$objects = Objects::where('user_id' , $this->user->id )->get();
}
function func_2(){
$objects = Objects::where('user_id' , $this->user->id )->get();
}
function func_3(){
$objects = Objects::where('user_id' , $this->user->id )->get();
}

主要是因为我不喜欢默认语法 \Auth::user() 但在升级到 5.4 之后这不再起作用了,我得到了 null $this->用户

虽然在其他方法中效果很好。基本上 \Auth::user()__construct 方法中返回 null 但在其他函数中工作正常。

最佳答案

作为doc说:

In previous versions of Laravel, you could access session variables or the authenticated user in your controller's constructor. This was never intended to be an explicit feature of the framework. In Laravel 5.3, you can't access the session or authenticated user in your controller's constructor because the middleware has not run yet.

那么试试这个:

public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
$this->user = Auth::user();

return $next($request);
});
}

关于php - laravel 5.4:无法在 __construct 方法中访问 Auth::user(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45055618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com