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

Published 11 months ago by nulele


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

Consider this Controller code:

public function __construct()
    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!



As i remember, Laravel build controller first. So anything in the constructor is call before the routes/controllers middlewares.

Edit :



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.

11 months ago (135,830 XP)


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

Please sign in or create an account to participate in this conversation.