为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
斯蒂芬大帝 2019-03-18 18:07:37
在服务提供者 ServiceProvider 无法获取到存储在session中的数据!使用request中的session会出现如下图的报错! dd全局辅助Session()输出的是空数组! 但是我的session在任何一个controller中dd都是有数据的! 请各位是什么原因!
查看完整描述

4 回答

?
HUX布斯

TA贡献1876条经验 获得超6个赞

你用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或者其他的服务,即使需要在这里操作,也应该是异步进行的,不管怎么说,就是要使用之前确保要使用的服务已经存在并创建完成。

查看完整回答
反对 回复 2019-03-18
?
侃侃尔雅

TA贡献1801条经验 获得超16个赞

laravel的session是中间件\Illuminate\Session\Middleware\StartSession::class,所以你在provider里面,这个中间件还没加载,就出现了这个问题。

查看完整回答
反对 回复 2019-03-18
  • 4 回答
  • 0 关注
  • 566 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信