snoopycodex/laravel-set-env-fork
Laravel package fork to set or update environment variables in your .env file at runtime. Useful for installers, admin panels, and setup flows that need to persist config changes (APP_URL, DB settings, etc.) without manual editing.
Installation:
composer require snoopycodex/laravel-set-env-fork
Publish the config file (if needed):
php artisan vendor:publish --provider="SnoopyCodeX\LaravelSetEnv\SetEnvServiceProvider"
First Use Case: Update a single environment variable via Artisan:
php artisan set:env APP_DEBUG=true
Verify the change by running:
php artisan config:clear && php artisan tinker
Then check in Tinker:
config('app.debug');
Where to Look First:
CI/CD Pipeline Integration: Dynamically set variables per environment in GitHub Actions, GitLab CI, or Jenkins:
# GitHub Actions example
- name: Set debug mode for staging
run: php artisan set:env APP_DEBUG=true APP_ENV=staging
Feature Flag Management: Toggle features without redeploying:
php artisan set:env FEATURE_NEW_CHECKOUT=true
Access in code:
if (env('FEATURE_NEW_CHECKOUT')) { ... }
Multi-Environment Overrides:
Use in bootstrap/app.php or a service provider to load environment-specific configs:
// app/Providers/AppServiceProvider.php
public function boot()
{
if (app()->environment('local')) {
\Artisan::call('set:env', [
'key' => 'APP_URL',
'value' => 'http://localhost:8000'
]);
}
}
Backup and Rollback:
Enable backups in config/setenv.php:
'backup' => true,
Then restore a previous value:
php artisan set:env APP_DEBUG=<previous_value> --restore
Safe Updates:
Restrict which variables can be modified by defining an allowed array in the config:
'allowed' => [
'APP_DEBUG',
'APP_ENV',
'QUEUE_CONNECTION',
'FEATURE_*', // Wildcard support
],
Block unauthorized changes with a middleware or policy.
Audit Logging: Log changes to a database table or file for compliance:
// Extend the SetEnvCommand to log changes
protected function handle()
{
$oldValue = $this->getEnvValue($this->argument('key'));
$this->callParentMethod(); // Original logic
\Log::info("Env var {$this->argument('key')} changed from {$oldValue} to {$this->argument('value')}");
}
Dynamic Configuration for Serverless: Use in AWS Lambda or Vercel deployments to set environment variables per invocation:
// In a Lambda function
$envKey = 'LAMBDA_INVOCATION_ID';
$envValue = $_ENV['_HANDLER'] ?? 'default';
\Artisan::call('set:env', compact('key', 'value'));
Laravel Events:
Trigger env updates on specific events (e.g., Deployed):
// app/Listeners/UpdateEnvOnDeploy.php
public function handle()
{
\Artisan::call('set:env', [
'key' => 'DEPLOY_TIMESTAMP',
'value' => now()->toDateTimeString()
]);
}
API-Driven Updates: Expose env updates via a controller (for admin panels):
// routes/api.php
Route::post('/env/{key}', function (Request $request, $key) {
\Artisan::call('set:env', [
'key' => $key,
'value' => $request->input('value')
]);
return response()->json(['success' => true]);
});
Testing: Reset env variables between tests:
// phpunit.xml
<env name="APP_ENV" value="testing"/>
Or use a setup method:
public function setUp(): void
{
\Artisan::call('set:env', [
'key' => 'APP_DEBUG',
'value' => 'false'
]);
parent::setUp();
}
File Permissions:
Ensure the .env file is writable by the web server/user running Artisan:
chmod 644 .env
Symptom: Command fails silently or throws Permission denied errors.
Caching Issues:
After updating .env, always run:
php artisan config:clear
Symptom: Changes not reflected in config() or env() calls.
Wildcard Overreach:
Wildcards in allowed (e.g., FEATURE_*) may accidentally permit sensitive variables. Explicitly list critical variables:
'allowed' => [
'FEATURE_NEW_CHECKOUT',
'FEATURE_EXPERIMENTAL_API',
],
Backup Bloat:
Enabling backups (backup: true) creates .env.backup files. Clean up old backups manually or automate with a cron job:
find /path/to/project -name ".env.backup" -mtime +7 -delete
Race Conditions:
Avoid concurrent writes to .env in multi-process environments (e.g., queues). Use locks or a mutex:
if (\File::lock('/path/to/.env.lock')) {
\Artisan::call('set:env', ['key' => 'QUEUE_WORKER', 'value' => 'true']);
\File::unlock('/path/to/.env.lock');
}
Silent Failures: Enable verbose output to debug:
php artisan set:env APP_DEBUG=true --verbose
Look for: File paths, permission checks, or validation errors.
Validation Errors:
If a variable is blocked by allowed, the command exits with:
The [VAR_NAME] environment variable is not allowed.
Fix: Add the variable to the allowed array in config or remove the restriction.
File Path Issues:
Customize the .env file path in config:
'file' => base_path('.env.local'), // Use a separate file for dynamic vars
Environment-Specific Files:
Use separate .env files for different environments (e.g., .env.staging, .env.prod) and point the package to the correct file:
'file' => base_path('.env.'.config('app.env')),
Type Safety:
Validate variable types before setting (e.g., ensure APP_DEBUG is boolean):
// Extend the SetEnvCommand
protected function validateValue($key, $value)
{
if ($key === 'APP_DEBUG' && !in_array(strtolower($value), ['true', 'false'])) {
throw new \InvalidArgumentException("APP_DEBUG must be true or false.");
}
}
Git Ignore:
Add backup files to .gitignore:
# .gitignore
.env.backup*
Laravel Forge/Vapor: For managed hosting, use the package in a pre-deploy hook (Forge) or deploy script (Vapor) to avoid runtime conflicts:
# forge/deploy.sh
php artisan set:env APP_URL=$APP_URL APP_ENV=production
Fallback Values:
Combine with Laravel’s env() helper for fallbacks:
$apiKey = env('API_KEY', 'default_fallback');
\Artisan::call('set:env', ['key' => 'API_KEY', 'value' => $apiKey]);
Security:
// app/Console/Kernel
How can I help you explore Laravel packages today?