Preventing a Console Command from Running on Production

This is a helper trait that I use when I have a Laravel console command that I’m using on development but would never want that command to run in a production environment. It’s always nice to have a system in place to prevent accidents from happening.

PreventsProduction.php

<?php

namespace App\Console;

trait PreventsProduction
{
    /**
     * Prevent the command from executing on production.
     */
    protected function preventOnProduction()
    {
        if ($this->laravel->environment() === 'production') {

            $this->error('Cannot run in production');

            exit;
        }
    }
}

Include the trait in your console command and use it like so:

SomeConsoleCommand.php

    use PreventsProduction;
    
    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->preventOnProduction();

        // Nothing past here will be run on production.
    }

Leave a Reply

Your email address will not be published. Required fields are marked *