简体   繁体   English

如何在其构造函数中为laravel控制器类定义全局变量

[英]how to define global variable for laravel controller class within its contructor

I want to assign some value, to a variable $user_detail here, fetched from database to be used throughout the controller class, eg user's detail. 我想为从数据库中获取的$user_detail变量分配一些值,以便在整个控制器类中使用,例如用户的详细信息。 Its Laravel 5.3 它的Laravel 5.3

private $user_detail;
public function __construct(){
    $this->user_detail=User::find(Auth::id());
}
public function index(){
    return $post_data=$this->user_detail;
}

From above code I get a blank screen. 从上面的代码中,我得到了一个空白屏幕。 How can I achieve this, or is there a better way to this? 我怎样才能做到这一点,或者有更好的方法吗? please suggest. 请提出建议。 Thanks 谢谢

You're trying to get currently authenticated user and pass it somewhere. 您正在尝试获取当前经过身份验证的用户并将其传递到某个地方。 But the thing is Laravel already did it for you and you can access an authenticated user from any part of an application by using auth()->user() object: 但是问题是Laravel已经为您做到了,您可以使用auth()->user()对象从应用程序的任何部分访问经过身份验证的用户:

{{ auth()->user()->name }}
{{ auth()->user()->email }}

You return a initialization, and that's why you see a blank page. 您返回一个初始化,这就是为什么您看到空白页的原因。 What you should do is initialize the variable and return the variable afterwards. 您应该做的是初始化变量,然后返回变量。 Your code would look like this. 您的代码如下所示。

public function index() {
    $post_data = $this->user_detail
    return $post_data;
}

This will initalize your variable first and afterwards you return the variable. 这将首先初始化您的变量,然后返回变量。

But like @alexeymezenin said, you already can get the logged in user object everywhere in your application by using auth()->user() . 但是就像@alexeymezenin所说的那样,您已经可以通过使用auth()->user()在应用程序中的任何位置获取登录的用户对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM