我试图在构造函数中访问 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
转到AppProvidersAppServiceProvider.php
在页面顶部包含外观
use IlluminateSupportFacadesAuth; use AppTrainingStatusRecord;并在boot方法中粘贴下面的代码
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.
参考 laravel/docs/5.4/providers#the-boot-method
希望能帮到你.
更多推荐
Laravel 5.4:在
发布评论