Search code examples
phplaravelcontrollerlaravel-5.3

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, e.g 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


Solution

  • 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 }}