In laravel5. *, sessionstart is placed in the web middleware, such as {code ...} according to the code for loading the middleware according to Route, we can know that the Controller calls the middleware only after being made. {code ...} at this time, the problem arises. I have a BaseController, which is being constructed... in laravel5. *, session start is placed in the web middleware, as shown in figure
/** * 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', ], ];
According to the code for loading the middleware by Route, we can know that the Controller calls the middleware only after being made.
/** * Get the middleware for the route's controller. * * @return array */ public function controllerMiddleware() { if (! $this->isControllerAction()) { return []; } return ControllerDispatcher::getMiddleware( $this->getController(), $this->getControllerMethod() ); }
At this point, the problem arises. I have a BaseController that will judge the user logon status in the constructor, if you have logged on, obtain the login user information and save it to $ this-> login_user_info for the subclass to call. if you make controller first, the session has no start, therefore, the user's session_id cannot be obtained in the constructor. part of the code is as follows:
/*** Control layer public method set * 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 (); // you can specify the template's global variable view () -> share (['login _ user_info '=> $ this-> login_user_info]);}
I have tested that a session can be obtained in middleware, because the StartSession middleware code has been executed at this time. as for why I want to do this, it is a long story, my project is an old project switching framework to laravel, so in order to maximize the original logic, and there are some strange ways to write, not using Auth, is there a way to get the session in the constructor? thank you for your help.