Laravel: How to access session value in AppServiceProvider?

放肆的年华 提交于 2019-12-30 17:25:26

问题


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


回答1:


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') );    
    });  
}

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




回答2:


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

AppServiceProvider.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

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

Shows "en_US" in the browser.



来源:https://stackoverflow.com/questions/35314031/laravel-how-to-access-session-value-in-appserviceprovider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!