沃梦达 / 编程问答 / php问题 / 正文

Laravel 5.4:在 __construct() 中获取登录用户 ID

Laravel 5.4 : Get logged in user id inside __construct()(Laravel 5.4:在 __construct() 中获取登录用户 ID)

本文介绍了Laravel 5.4:在 __construct() 中获取登录用户 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在构造函数中访问 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.

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

希望能帮到你.

这篇关于Laravel 5.4:在 __construct() 中获取登录用户 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Laravel 5.4:在 __construct() 中获取登录用户 ID

基础教程推荐