简体   繁体   中英

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. Its 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:

{{ 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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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