laravel 5.4:无法在 __construct 方法中访问 Auth::user()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45055618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
laravel 5.4 : cant access Auth::user() in the __construct method
提问by hretic
In previous versions of Laravel, in the controllers which I needed to access logged user in all the methods I used to do something like this:
在以前版本的 Laravel 中,在我需要使用所有方法访问登录用户的控制器中,我曾经执行过以下操作:
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();
}
Mostly because I don't like the default syntax \Auth::user()
but after upgrading to 5.4 this doesn't work anymore and I get null
from $this->user
主要是因为我不喜欢默认语法,\Auth::user()
但升级到 5.4 后,这不再起作用,我null
从$this->user
It works fine in other methods though. Basically \Auth::user()
return null
in the __construct
method but works fine in the other functions.
不过,它在其他方法中运行良好。基本上在方法中\Auth::user()
返回null
,__construct
但在其他函数中工作正常。
回答by Maraboc
As the docsays :
正如医生所说:
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.
在以前版本的 Laravel 中,您可以在控制器的构造函数中访问会话变量或经过身份验证的用户。这从未打算成为该框架的显式特征。在 Laravel 5.3 中,您无法在控制器的构造函数中访问会话或经过身份验证的用户,因为中间件尚未运行。
So try this :
所以试试这个:
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
$this->user = Auth::user();
return $next($request);
});
}
回答by Manjeet Vishwakarma
You Have To define Auth method before you load your class as you use your namespace.See the example below:
在使用命名空间时,您必须在加载类之前定义 Auth 方法。请参见下面的示例:
namespace App\Http\Controllers\Admin;
use Illuminate\Support\Facades\Input;
use Auth;
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();
}
And After you can clean your cache if required. php artisan config:cache
如果需要,您可以在之后清理缓存。php工匠配置:缓存