Laravel 5.4:在__construct()中登录用户ID [英] Laravel 5.4 : Get logged in user id inside __construct()
问题描述
我正在尝试访问构造函数内的Auth::user()->id;
,但它总是返回错误试图获取非对象的属性.我在laravel文档中研究到,在构造函数内部无法访问Session,并且还在SO上进行搜索.我需要在构造函数中登录用户ID,因为我必须从数据库中获取数据并使其可用于其所有方法.我当前的代码是:
I am trying to access Auth::user()->id;
inside constructor but it always return the error Trying to get property of non-object. I study in the laravel documentation that Session is not accessible inside constructor and also search on SO for this. I need logged in user id inside constructor because I have to fetch data from database and make it available for all its method. My current code is :
public function __construct(){
$this->middleware('auth');
$induction_status = TrainingStatusRecord::where('user_id',Auth::user()->id)->where('training','=','induction')->get();
View::share('ind_status',$induction_status);
}
是否有任何方法(简便方法)在构造函数中获取用户ID.
Is there any way (easy way) to get logged in user id inside constructor.
我将不胜感激.
谢谢
推荐答案
在视图 AppServiceProvider 中共享变量是一种很好的方法
To share a variable in view AppServiceProvider is a good approach
转到 App \ Providers \ AppServiceProvider.php
在页面顶部包含外观
use Illuminate\Support\Facades\Auth;
use App\TrainingStatusRecord;
并在启动方法中粘贴以下代码
and paste below code in boot method
view()->composer('*', function($view){
if(Auth::user()){
$induction_status = TrainingStatusRecord::where('user_id',Auth::user()->id)->where('training','=','induction')->get();
View::share('induction_status',$induction_status);
}
});
现在,您将可以在应用程序中获取变量$induction_status
.
Now you will be able to get your variable $induction_status
in your app.
参考 https://laravel.com /docs/5.4/providers#the-boot-method
希望它会对您有所帮助.
Hope it will help you.
这篇关于Laravel 5.4:在__construct()中登录用户ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!