Laravel-会话变量在服务提供者中为null [英] Laravel - Session variable is null in Service Provider

查看:68
本文介绍了Laravel-会话变量在服务提供者中为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用AppServiceProvider类与所有视图共享会话值.

I'm trying to share a Session value with all views using AppServiceProvider class.

boot()函数中,我说:view()->share('key', Session::get('key'));

但是,值是null.可能是什么问题?在我设置的控制器中,它可以正常工作.即使删除了Session::put()行,该值仍在会话中(显然).

But, the value is null. What can be the problem? In the Controller I'm setting it, it works fine. Even after removing the Session::put() line, the value is still in the session (obviously).

推荐答案

在Laravel中,会话是在由此类处理的中间件中初始化的:

In Laravel session is initialized in a middleware that is handled by this class:

\Illuminate\Session\Middleware\StartSession::class

启动服务提供商时,尚未执行该中间件,因为所有中间件都在服务提供商启动阶段之后执行

When the service providers are booted, this middleware has not been executed, because all the middlewares execute after the service providers boot phase

因此,您可以创建中间件并从那里共享会话变量,而不是从服务提供商那里共享变量,或者可以在服务提供商中使用带有回调的视图编写器:

So, instead of sharing the variable from a service provider, you can create a middleware and share the session variable from there, or you can use a view composer with a callback in your service provider:

public function boot()
{
    view()->composer('*', function ($view) 
    {
        //this code will be executed when the view is composed, so session will be available
        $view->with('key', \Session::get('key') );    
    });  
}

这将起作用,因为当中间件已经执行时,将在构成视图之前调用回调,因此会话将可用

This will work, as the callback will be called before the views are composed, when the middleware has already been executed, so session will be availabe

通常,请注意中间件的执行顺序:如果要从中间件访问会话,则应在Laravel的StartSession::class中间件

In general, pay attention at your middleware's execution order: if you want to access the session from a middleware, that should execute after Laravel's StartSession::class middleware

这篇关于Laravel-会话变量在服务提供者中为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆