Laravel 5.3: How to use Auth in Service Provider?

后端 未结 2 1559
轮回少年
轮回少年 2021-01-16 10:42

I am passing a value in shared view by taking value from table. I need to know user ID for the purpose but Auth::check() returns false. How do I do it? Below is

2条回答
  •  [愿得一人]
    2021-01-16 11:12

    OK turns out that ServiceProviders are not place for such things. The best thing is a Middleware. So if you want to call Auth, create middleware and pass value to views.

    public function handle($request, Closure $next)
        {            
            $basket_count = 0;
            if ($this->auth) { //always false
                $loggedin_user_id = $this->auth->user()->id;
                $basket_count = Cart::getBasketCount($loggedin_user_id);
            }
            view()->share('basket_count', $basket_count);
    
            return $next($request);
        }
    

提交回复
热议问题