Laravel-如何在AppServiceProvider中获取当前用户 [英] Laravel - How to get current user in AppServiceProvider
问题描述
因此,通常我会使用Auth::user()
来获取当前用户,并且在确定用户是否实际登录Auth::check
时会使用它.但是,这似乎在我的AppServiceProvider
中不起作用.我正在使用它在所有视图之间共享数据.我在登录时同时var_dump
和var_dump
都得到了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
如果出于某些其他原因要在服务提供商中进行操作,则可以使用带有回调的View Composer ,如下所示:
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屋!