Laravel:如何在AppServiceProvider中访问会话值? [英] Laravel: How to access session value in AppServiceProvider?
问题描述
有什么方法可以访问AppServiceProvider
中的Session值?我想在所有视图中全局共享会话价值.
Is there any way available to access Session values in AppServiceProvider
? I would like to share session value globally in all views.
推荐答案
您不能直接从服务提供商读取会话:在Laravel中,该会话由StartSession
中间件处理,该中间件在所有服务提供商启动阶段之后执行
You can't read session directly from a service provider: in Laravel the session is handled by StartSession
middleware that executes after all the service providers boot phase
如果您想与所有视图共享会话变量,则可以使用视图编辑器来自您的服务提供商:
If you want to share a session variable with all view, you can use a view composer from your service provider:
public function boot()
{
view()->composer('*', function ($view)
{
$view->with('your_var', \Session::get('var') );
});
}
作为第二个参数传递给作曲家的回调将在呈现视图时被调用,因此StartSession
届时将已经执行
The callback passed as the second argument to the composer will be called when the view will be rendered, so the StartSession
will be already executed at that point
这篇关于Laravel:如何在AppServiceProvider中访问会话值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!