0

I use $user = Auth::user(); in almost every route and within almost every view. I have dozens of routes and dozens of views so constantly having to repeat $user = Auth::user(); feels wrong.

Is there a way that I can just call $user = Auth::user(); once and then have it available across the entire application, including within routes and views?

I'm using Laravel 5.2.

1 Answers1

3

In your app/Providers/AppServiceProvider.php

within the boot method, paste this code. This will make $user variable accessible in all your views

view()->share('user', auth()->user());

Or if you don't like helper functions then you can instead use facades

View::share('user', Auth::user());

and import it at the top

use View;

For your whole app access, you can make use of config global helper.

put this line of code in your boot method

config('user', auth()->user());

to access it any where, use this

config('user');
Zayn Ali
  • 4,765
  • 1
  • 30
  • 40
  • 1
    I would like to expand on this: Doing this allows you to use the `$user` variable throughout your entire application without any issues. If something happened and `Auth::user()` were no longer available, you'd have to go change ten/hundred/thousand(s) of lines of code to reflect that. Aliasing this and making it application wide allows you to only make that change in 1 place. This is a similar concept to the [repository pattern](https://msdn.microsoft.com/en-us/library/ff649690.aspx). – Ohgodwhy Aug 06 '16 at 04:11
  • This only passes it to all VIEWS, but not the entire app (like routes). – user6684704 Aug 06 '16 at 04:29
  • @ZaynAli I tried to implement your answer, but it returns null for user. It seems like this only stores the Auth::user() value in the start which is null as user is not logged in.... Not sure about it though.... – jaysingkar Aug 22 '16 at 19:05