Skip to content

Instantly share code, notes, and snippets.

@chrispian
Created February 18, 2025 14:28
Show Gist options
  • Save chrispian/b933e5d9432488df2b058fbebd2151d1 to your computer and use it in GitHub Desktop.
Save chrispian/b933e5d9432488df2b058fbebd2151d1 to your computer and use it in GitHub Desktop.
Laravel - Prevent Command Execution on Production
<?php
/*
*
* USAGE: Add PreventOnProduction trait to your command. By default
* this will prevent the command from being run on production environments.
*
* OPTIONAL: Override the default by definining the $prohibitedEnvironments array.
* eg: $prohibitedEnvironments = ['prodcution', 'staging'];
*
* Tested on Laravel 10.x but should work with 11 without issue
*
*
*/
namespace App\Traits;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
trait PreventOnProduction
{
protected array $defaultProhibitedEnvironments = ['production']; // Default if not overridden
public function run(InputInterface $input, OutputInterface $output): int
{
// Determine which environments should be blocked
$prohibitedEnvironments = $this->prohibitedEnvironments ?? $this->defaultProhibitedEnvironments;
// Check if the current environment is in the prohibited list
if (in_array(app()->environment(), $prohibitedEnvironments)) {
$output->writeln("<error>❌ This command cannot be run in the " . app()->environment() . " environment.</error>");
return Command::FAILURE;
}
// If not prohibited, proceed with normal execution
return parent::run($input, $output);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment