laravel使用服务提供者使用session问题!

在服务提供者 ServiceProvider 无法获取到存储在session中的数据!
使用request中的session会出现如下图的报错!
https://img1.mukewang.com/5c8f6de80001071408000098.jpg

dd全局辅助Session()输出的是空数组!

但是我的session在任何一个controller中dd都是有数据的!

请各位是什么原因!

斯蒂芬大帝
浏览 567回答 4
4回答

HUX布斯

你用session的地方,session服务还不存在呐。 ServiceProvider里面有两个方法: register boot 它们的意义使不同的,文档说法如下: register As mentioned previously, within the register method, you should only bind things into the service container. You should never attempt to register any event listeners, routes, or any other piece of functionality within the register method. Otherwise, you may accidentally use a service that is provided by a service provider which has not loaded yet. 在register方法中,仅仅只能往容器上做绑定服务操作,不能尝试使用框架内的其他服务,这个时候其他的服务有没有创建完毕是无法保证的。 boot This method is called after all other service providers have been registered, meaning you have access to all other services that have been registered by the framework 这个方法是在所有ServiceProvider注册完毕后执行的,在这里,可以调用框架已经注册创建好的其他服务的。 另外,你不应该直接在这里使用session或者其他的服务,即使需要在这里操作,也应该是异步进行的,不管怎么说,就是要使用之前确保要使用的服务已经存在并创建完成。

侃侃尔雅

laravel的session是中间件\Illuminate\Session\Middleware\StartSession::class,所以你在provider里面,这个中间件还没加载,就出现了这个问题。
打开App,查看更多内容
随时随地看视频慕课网APP