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

Published 4 months ago by nulele

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?

Parasoul

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

Edit :

https://laravel-news.com/controller-construct-session-changes-in-laravel-5-3

nulele

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.

d3xt3r
d3xt3r
4 months ago (146,230 XP)

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

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.