Laravel - How to get current user in AppServiceProvider

主宰稳场 提交于 2019-11-27 05:48:23

问题


So I am usually getting the current user using Auth::user() and when I am determining if a user is actually logged in Auth::check. However this doesn't seem to work in my AppServiceProvider. I am using it to share data across all views. I var_dump both Auth::user() and Auth::check() while logged in and I get NULL and false.

How can I get the current user inside my AppServiceProvider ? If that isn't possible, what is the way to get data that is unique for each user (data that is different according to the user_id) across 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'));
    }

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/37372357/laravel-how-to-get-current-user-in-appserviceprovider

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