Skip to content

Controller is constructed before route middleware are executed #44177

@christhomas

Description

@christhomas

Version: Laravel 9
PHP: 8.1

The problem that I'm having is that Laravel constructs the controller object and it's entire dependency injected set of parameters and the entire tree of other dependencies too. Before the middleware are run through and that means that middleware can't affect those dependencies by adjusting the request or setting other parameters that would affect how the AppServiceProvider can create the dependencies.

Is there a reason why the Controller is constructed before the route middleware are triggered and passed through? It seems like this is backwards, since the route middleware are supposed to do things based on the route and typically middleware affect how the system will run, THEN the controller executes and does the work.

But if the controller is created first, then all it's tree of dependencies are created too, direct parameters result in objects created, but those objects also have constructors, resulting in more objects being created, etc, etc. This entire tree of objects is created before the middleware has a chance to even do it's job.

This results in my rest api as a system which throws exceptions because one of the dependencies deep in the tree tries to do something that it's not allowed. Something the middleware would prevent by adjusting the request based on circumstances such as permissions or auth capabilities.

So whats the solution to this? I see this issue was talked about since 2016, but I can't think that I'm the only person who thought of this problem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions