Search code examples
phplaravellaravel-5laravel-authorization

Laravel - Why middleware get skipped?


Assume user have logged out and user visit this page http://domain.com/admin

In the controller, I have __construct method like this:

public function __construct() {
  $this->middleware('auth');
  dd("Hello World");
}

Why does it show "Hello World" on the screen? $this->middleware should be exectuted first and redirect to Login Page via auth middleware because User have not logged in.

However, If I remove dd("Hello World"); like this:

public function __construct() {
  $this->middleware('auth');
}

It work fine and redirected to a login page.


Solution

  • Because $this->middleware method actually binds your controller methods/actions to the auth middleware that you are defining. it doesn't executed at this point instead when your route gets called.

    Ref: Laravel docs

    it is more convenient to specify middleware within your controller's constructor. Using the middleware method from your controller's constructor, you may easily assign middleware to the controller's action.

    and while hitting this route: http://domain.com/admin. In reality, your controller's index method fires after the controller object gets instantiated and binds the middleware.