Laravel - How to get current user in AppServiceProvider Laravel - How to get current user in AppServiceProvider php php

Laravel - How to get current user in AppServiceProvider


Laravel session is initialized in a middleware so you can't access the session from a Service Provider, because they execute before the middleware in the request lifecycle

You should use a middleware to share your varibles from the session

If for some other reason you want to do it in a service provider, you could use a view composer with a callback, like this:

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 being composed, so middlewares will be already executed and session will be available


In AuthServiceProvider's boot() function write 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 - in all of your views $currentUser variable is available.

Then, from view file {{ currentUser }} will give you the User info if user is authenticated otherwise null.


As per my Laravel 7 experience, Auth::user() does not work in AppServiceProvider.php instead the helper function auth()->user() did the trick for me.

public function boot()    {        if (auth()->check()) {            View::composer('layout.app', function ($view) {                $userName = auth()->user()->name;                $view->with(['userName' => $userName]);            });        }    }