Laravel - 如何在 AppServiceProvider 中获取当前用户
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37372357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel - How to get current user in AppServiceProvider
提问by Codearts
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
.
所以我通常让当前用户使用Auth::user()
,当我确定用户是否实际登录时Auth::check
。但是,这在我的AppServiceProvider
. 我正在使用它在所有视图中共享数据。我var_dump
既Auth::user()
和Auth::check()
登录时,我得到NULL
和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.
如何让当前用户进入我的AppServiceProvider
? 如果这是不可能的,那么user_id
在所有视图中获取每个用户唯一的数据(根据 不同的数据)的方法是什么。这是我的澄清代码。
if (Auth::check()) {
$cart = Cart::where('user_id', Auth::user()->id);
if ($cart) {
view()->share('cart', $cart);
}
} else {
view()->share('cartItems', Session::get('items'));
}
回答by Moppo
Laravel session is initialized in a middleware so you can't access the session from a Service Provider, because they execute beforethe middleware in the request lifecycle
Laravel 会话在中间件中初始化,因此您无法从服务提供者访问会话,因为它们在请求生命周期中的中间件之前执行
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 composerwith 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
只有在实际组合视图时才会执行回调,因此中间件将已经执行并且会话将可用
回答by Maniruzzaman Akash
In AuthServiceProvider
's boot()
function write these lines of code
InAuthServiceProvider
的boot()
函数写这几行代码
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.
这*
意味着 - 在您的所有视图中$currentUser
变量都可用。
Then, from view file {{ currentUser }}
will give you the User info if user is authenticated otherwise null.
然后,{{ currentUser }}
如果用户已通过身份验证,则视图文件将为您提供用户信息,否则为空。