Laavel 5.3 session in controller
As you all know, in L5.3 there is no possibility to access the session in the controller constructor. My question is how the 'auth' middleware will work if it cannot access the session? How can it figure if the user is authenticated or not if it cannot access the session?
It's the StartSession middleware that populates the session object and the Authenticate middleware that populate the user object.
I know the middlewares get executed before the controller's execution, but that doesn't mean the controller is resolved (instantiated) after the middleware execution.
At a very high level, the controller and the middlewares got instantiated first (aka constructor is called) then the middleware got executed (handle() gets called), then the controller's action gets executed (aka $controller->whatever() gets called).
SessionGuard is the part of the authentication that needs session's information in the constructor, but it got instantiated in the handle() method of Authenticate, which runs after the handle method of StartSession (which populates the session).
With an example:
// Consider these as global variables
$session = null;
$user = null;
$middlewares = [];
// Step 1: Create the controller
// If we ask for the session here, we get null. The controller constructor can add elements to $mdidlewares.
$controller = new ExampleController(/** dependences **/);
// Step 2: Create the middlewares
$middlewares[] = new StartSession(/** dependences **/);
$middlewares[] = new Authenticate(/** dependences **/);
// Step 3: Run Middlewares
foreach ($middlewares as $middleware) {
$middleware->handle();
/*
The session middleware populates the $session variable here.
Then the Authenticate middleware asks for $session (already populated because StartSession is before it), and retrieves the user populating $user.
*/
}
// Step 4: Run Controller
// Here session and user have been set, so we can ask for them.
$controller->whatever();
This is ages away from Laravel code, but it might help you understand the succession of events.
Please or to participate in this conversation.