2

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

Gaurav Rai
  • 900
  • 10
  • 23
  • `$this->user_detail = auth()->user();` or not define it at all from **construct** and use `auth()->user()` wherever you need – zgabievi Jan 27 '17 at 11:25

2 Answers2

3

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 }}
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • Amazing! just one more query, suppose if I have another table related, how I'm going to fetch that with auth() e.g at present code looks like 'User::with('hospital')->find(Auth::id());' user belongs to hospital – Gaurav Rai Jan 27 '17 at 11:39
  • @GauravRai in this case use [lazy eager loading](https://laravel.com/docs/5.3/eloquent-relationships#lazy-eager-loading), like `auth()->user()->load('hospital')` – Alexey Mezenin Jan 27 '17 at 11:40
  • Could you help me here http://stackoverflow.com/questions/41690759/laravel-flash-or-session-messages-not-expiring – Gaurav Rai Jan 27 '17 at 16:53
0

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

Roberto Geuke
  • 532
  • 4
  • 14