Laravel - How to get the current user in AppServiceProvider

So, I usually get the current user using Auth::user() and when I determine if the user is really registered with Auth::check . However, this does not work in my AppServiceProvider . I use it to exchange data in all views. I var_dump and Auth::user() and Auth::check() during login, and I get NULL and false .

How can I get the current user inside my AppServiceProvider ? If this is not possible, in what way to get data that is unique to each user (data that differs from each other according to user_id ) in all views. Here is my code for clarification.

 if (Auth::check()) { $cart = Cart::where('user_id', Auth::user()->id); if ($cart) { view()->share('cart', $cart); } } else { view()->share('cartItems', Session::get('items')); } 
+6
source share
2 answers

The Laravel session is initialized in the middleware, so you cannot access the session from the service provider, as they execute up to the middleware in the request life cycle

You must use middleware to exchange your variables from the session.

If for any other reason you want to do this with your service provider, you can use view composer with a callback, for example:

 public function boot() { //compose all the views.... view()->composer('*', function ($view) { $cart = Cart::where('user_id', Auth::user()->id); //...with this variable $view->with('cart', $cart ); }); } 

The callback will be executed only when the view is actually composed, so middlewares will already be executed and the session will be available

+9
source

In AuthServiceProvider boot() function writes these lines of code

 public function boot() { view()->composer('*', function($view) { if (Auth::check()) { $view->with('currentUser', Auth::user()); }else { $view->with('currentUser', null); } }); } 

Here * means - the variable $currentUser is available in all your views.

Then, from a file of the form {{ currentUser }} you will receive information about the user if the user is authenticated otherwise null.

0
source

All Articles