Laravel 5.3:如何在服务提供商中使用Auth? [英] Laravel 5.3: How to use Auth in Service Provider?
本文介绍了Laravel 5.3:如何在服务提供商中使用Auth?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在通过从表中获取值在共享视图中传递值.我需要知道用户ID,但Auth::check()
返回false.我该怎么做?下面是代码:
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 code:
public function boot()
{
$basket_count = 0;
if (Auth::check()) { //always false
$loggedin_user_id = Auth::user()->id;
$basket_count = Cart::getBasketCount();
}
view()->share('basket_count', $basket_count);
}
推荐答案
确定,ServiceProviders
不是放置此类内容的地方.最好的是Middleware
.因此,如果您要调用Auth,请创建中间件并将值传递给视图.
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);
}
这篇关于Laravel 5.3:如何在服务提供商中使用Auth?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文