Laravel - 如何在 AppServiceProvider 中获取当前用户 [英] Laravel - How to get current user in AppServiceProvider
问题描述
所以我通常使用 Auth::user()
获取当前用户,当我确定用户是否实际登录 Auth::check
时.但是,这在我的 AppServiceProvider
中似乎不起作用.我正在使用它在所有视图中共享数据.我 var_dump
Auth::user()
和 Auth::check()
在登录时我得到 NULL
> 和 false
.
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
.
如何在我的 AppServiceProvider
中获取当前用户?如果这是不可能的,那么如何在所有视图中获取每个用户唯一的数据(根据 user_id
不同的数据).这是我的澄清代码.
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'));
}
推荐答案
Laravel 会话在中间件中初始化,因此您无法从服务提供者访问会话,因为它们在中间件之前 执行在请求生命周期中
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
这篇关于Laravel - 如何在 AppServiceProvider 中获取当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!