在以前版本的 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/