Controller Constructors and the Artisan route:list command

Posted 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?

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

Reply to

Use Markdown with GitHub-flavored code blocks.