Laravel 5.4 : Get logged in user id inside __construct()

倾然丶 夕夏残阳落幕 提交于 2019-11-26 17:17:22

问题


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);
}  

Is there any way (easy way) to get logged in user id inside constructor.

I will appreciate any help.

Thank You


回答1:


To share a variable in view AppServiceProvider is a good approach

Go to App\Providers\AppServiceProvider.php

Include facade on top of the page

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);
        }
    });

Now you will be able to get your variable $induction_status in your app.

Reference https://laravel.com/docs/5.4/providers#the-boot-method

Hope it will help you.




回答2:


To solve this problem App\Providers\AppServiceProvider was indeed my first guess. This would work mostly but with an exception to access Session data.

So If you try to access Session data within boot method of AppServiceProvider you will get null. So to do this so it works perfectly good in any case Middleware is a good option. You can write this logic of sharing a variable to all your desired views. Just create a middleware and include that in your route or routegroup .




回答3:


Try this:

public function __construct(){
    $this->middleware(function ($request, $next) {
        $induction_status = TrainingStatusRecord::where('user_id',Auth::user()->id)->where('training','=','induction')->get();
    }
    View::share('induction_status',$induction_status);
}


来源:https://stackoverflow.com/questions/43133361/laravel-5-4-get-logged-in-user-id-inside-construct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!