Laravel - How to get current user in AppServiceProvider

一曲冷凌霜 提交于 2019-11-28 08:25:38

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!