In laravel5.*, session start is placed in the Web middleware, such as
/** * 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', ], ];
And according to the code of the route loading middleware, it is known that the controller is called before the middleware
/** * Get the middleware for the route's controller. * * @return array */ public function controllerMiddleware() { if (! $this->isControllerAction()) { return []; } return ControllerDispatcher::getMiddleware( $this->getController(), $this->getControllerMethod() ); }
This time the problem comes, I have a basecontroller, in the constructor will determine the user login status, if you have logged on to get the login user information saved to $this->login_user_info for the subclass call, if you first make Controller,session has not yet start, so in the constructor it is not possible to get the session_id to the logged-in user, some of the code is as follows
/** * 控制层公有方法集合 * 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]); } }
I tested in middleware can get the session, because this time has executed the Startsession middleware code, as for why I do this is a long story, my project is an old project to switch framework to Laravel, So in order to maximize the original logic, and there are some strange writing, no use of auth, these for the moment, there is no way to get the session in the constructor, ask you to help the great God, thank you