nulele's avatar

Execution order in controller's constructor with middleware (Laravel 5.4)

Hello,

I'm facing a weird problem on execution order inside a controller's constructor.

Consider this Controller code:

public function __construct()
{
    $this->middleware(MyStupidMiddleware::class);
    echo "2";
}

And MyStupidMiddleware code:

public function handle($request, Closure $next)
{
    echo "1";

    return $next($request);
}

When I execute the request, I get 2 and 1!

WHY?

0 likes
3 replies
nulele's avatar

Thank you Parasoul but your link is about using sessions in controller's constructor... maybe I'm wrong but this has nothing to do with my problem that it seems more general.

My problem is about the execution order of code in the constructor itself.

1 like
d3xt3r's avatar

$this->middleware(MyStupidMiddleware::class);

It does not actually execute the middleware code but add it to the list to be executed later ...

1 like

Please or to participate in this conversation.