时间:2021-07-01 10:21:17 帮助过:6人阅读
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class, //<---------
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
并且根据Route加载中间件的代码可以得知Controller是在被make之后才调用中间件
/**
* Get the middleware for the route's controller.
*
* @return array
*/
public function controllerMiddleware()
{
if (! $this->isControllerAction()) {
return [];
}
return ControllerDispatcher::getMiddleware(
$this->getController(), $this->getControllerMethod()
);
}
这个时候问题就来了,我有一个BaseController,在构造函数里面会判断用户登录状态,如果已经登录就获取登录用户信息保存到$this->login_user_info中供子类调用,如果先make controller,session还没有start,因此在构造函数中是无法获取到登录用户的session_id,部分代码如下
/**
* 控制层公有方法集合
* Class BaseController
*/
abstract class BaseController extends Controller
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public $login_user_info;
public $login_subuser_info;
public function __construct()
{
$this->userModel = app(UserModel::class);
if (session()->get('user_id')) {
$this->login_user_info = $this->userModel->getLoginUser();
//设置模板全局变量
view()->share(['login_user_info' => $this->login_user_info]);
}
}
我测试过在middleware中是可以得到session,因为这个时候已经执行了StartSession中间件代码,至于我为什么要这么做就说来话长,我的项目是一个老项目切换框架到laravel,所以为了最大限度的保持原有逻辑,并且还有一些奇奇怪怪的写法,没有采用Auth,这些暂且不论,有没有办法可以在构造函数中得到session,求各位大神帮忙,谢谢