Controller Constructors and the Artisan route:list command

Published 1 year ago by zelaza

The Artisan route:list command seems to need to instantiate all of your Controllers, so if you ever put anything in a Controller constructor that causes an error when the constructor gets called from the command line, you will break your php artisan route:list command, which is not a happy thing.

You can usually prevent this by carefully avoiding putting anything in any of your Controller constructors that would cause an error when run from the artisan command line.

However, there are certain situations where it makes really good programming sense to put something in a Controller that will take an error when called via artisan route:list (e.g. Controllers with several methods that all require information from a real http request, which does not exist when the constructor is called by artisan).

In these cases I have been forced to put some logic in the Controller constructor that avoids taking the error by returning immediately when it detects that the constructor is being called by Artisan, e.g.:

    public function __construct(Request $request)
    {

        if (basename($_SERVER['SCRIPT_NAME']) == 'artisan') {
            return null;
        }

        ...

I don't really like the above approach for a number of reasons, but it works.

Is there a "better" way to solve this problem?

codenex
codenex
1 year ago (32,380 XP)

Hmm. I'd have to think about it. Honestly I haven't put anything in my controller constructors that would cause an error when run from the command line.

WebKenth

Can you give an example of when you actually WANT an error in your controllers constructor?

Seems like you should catch anything unwanted before you ever call the controller which is pretty much what middleware is for.

Mittensoff

Would making a function that takes in routes and controller actions (functions) as arguments and simulates what you need of artisan route:list?

You could define all that you need done there.

Art

I'm having the same issue. I'm retrieving oauth api user in constructor, as i need it in all controller methods.

Cronix
Cronix
1 week ago (794,690 XP)

@art sounds like something that could be done in middleware

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