Laravel 5.4: login user id inside __construct ()
I'm trying to access the constructor Auth::user()->id;
internally, but it always returns an error Trying to get a property of a non-object . I am researching in the laravel documentation that the session is not available inside the constructor and also search on SO for this. I need to login to the user id inside the constructor because I need to get data from the database and make it available to all of its method. My current code:
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 a way (easy way) to enter the user id inside the constructor.
Any help would be appreciated.
thank
source to share
To share the visible variable of AppServiceProvider is a good approach
Go to App \ Providers \ AppServiceProvider.php
Include facade at the top of the page
use Illuminate\Support\Facades\Auth;
use App\TrainingStatusRecord;
and paste below code into 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 should be able to get your variable $induction_status
in your application.
Link https://laravel.com/docs/5.4/providers#the-boot-method
Hope this helps you.
source to share
To solve this App\Providers\AppServiceProvider
really was my first guess. This will work mostly, but with an exception for data access Session
.
So, if you try to access the Session
data in the loading method of the AppServiceProvider , you get null
. So to do this, it works great anyway Middleware
- a good option. You can write this variable exchange logic to all of your desired views. Just create Middleware
and include it in route
or routegroup
.
source to share