Protect or disable laravel artisan commands in production

While working on a product at VentureCraft, I wanted to make sure that there was no way I could accidentally screw myself over by running something like migrate:refresh in production. I put up a teaser on twitter which got some good attention so I thought I’d share the nasty code I used to achieve this.

The tweet:

The code:

At this stage, all I’m doing is adding a snippet of code to the top of my app/artisan.php file, which performs the check. At a later stage I planned on moving this to a package so I can use it in other projects, however I received the following tweet from Taylor which hopefully will make that redundant and he’ll just build it into the core (a touch more elegantly I’m sure):

What’s ore, in the package I’d planned on allowing to pick and choose which commands are protected in which environment based on a config file, the following hopefully will take care of that too:

Update

Stoked to see that this has indeed been added into the core, as a trait you can add to your own commands

  • Pingback: Protect or disable laravel artisan commands in production | Chris Duell (www.chrisduell.com) | gabconcepcion

  • http://burak.ca/ Burak Erdem

    Thanks for this great tip. It works great but I have one question. I’m trying to run migrations via Git hooks, so I need to answer this question “y” automatically via Git post-update hook.

    It’s OK to warn user when a migration command is run manually but for automatic commands, there needs to be a flag. I’m not sure if this a good practice but is there a way to append “y” to the artisan command like;

    $ php artisan migrate –env=production -y

    The above command is not working as it says “The “-y” option does not exist”.

  • http://feliciousx.github.io/ Churchill Lee

    So right now with the added trait how would I make `php artisan migrate:foo` to ask for confirmation?

    • http://chrisduell.com/ Chris Duell

      It should ask that if you are in production, if not perhaps ask in the laravel forms for help at https://laravel.io

      • pakuize

        well if it worked as intended trying to drill down right now, but this does not only happen in production but also when the env is set to local or dev.
        Even though Artisan can see that the env is local or dev.