Laravel:如何访问 AppServiceProvider 中的会话值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35314031/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:13:00  来源:igfitidea点击:

Laravel: How to access session value in AppServiceProvider?

phplaravelsessionlaravel-5laravel-5.1

提问by Qazi

Is there any way available to access Session values in AppServiceProvider? I would like to share session value globally in all views.

有什么方法可以访问 Session 中的值AppServiceProvider吗?我想在所有视图中全局共享会话值。

回答by Moppo

You can't read session directly from a service provider: in Laravel the session is handled by StartSessionmiddleware that executes after all the service providers boot phase

您不能直接从服务提供者读取会话:在 Laravel 中,会话由StartSession在所有服务提供者启动阶段之后执行的中间件处理

If you want to share a session variable with all view, you can use a view composerfrom your service provider:

如果要与所有视图共享会话变量,可以使用服务提供商提供的视图编辑器

public function boot()
{
    view()->composer('*', function ($view) 
    {
        $view->with('your_var', \Session::get('var') );    
    });  
}

The callback passed as the second argument to the composer will be called when the view will be rendered, so the StartSessionwill be already executed at that point

作为第二个参数传递给 Composer 的回调将在渲染视图时被调用,因此该回调StartSession将在该点被执行

回答by kalatabe

The following works for me on Laravel 5.2, is it causing errors on your app?

以下在 Laravel 5.2 上对我有用,是否会导致您的应用出错?

AppServiceProvider.php

应用服务提供者.php

class AppServiceProvider extends ServiceProvider
{
/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    \Session::put('lang', 'en_US');
    view()->share('lang', \Session::get('lang', 'de_DE'));
}

/**
 * Register any application services.
 *
 * @return void
 */
public function register()
{
    //
}
}

home.blade.php

主页.blade.php

<h1>{{$lang}}</h1>

Shows "en_US" in the browser.

在浏览器中显示“en_US”。