Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Set Env Fork Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require snoopycodex/laravel-set-env-fork
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="SnoopyCodeX\LaravelSetEnv\SetEnvServiceProvider"
    
  2. 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');
    
  3. Where to Look First:


Implementation Patterns

Usage Patterns

  1. 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
    
  2. Feature Flag Management: Toggle features without redeploying:

    php artisan set:env FEATURE_NEW_CHECKOUT=true
    

    Access in code:

    if (env('FEATURE_NEW_CHECKOUT')) { ... }
    
  3. 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'
            ]);
        }
    }
    
  4. 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
    

Workflows

  1. 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.

  2. 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')}");
    }
    
  3. 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'));
    

Integration Tips

  1. 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()
        ]);
    }
    
  2. 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]);
    });
    
  3. 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();
    }
    

Gotchas and Tips

Pitfalls

  1. 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.

  2. Caching Issues: After updating .env, always run:

    php artisan config:clear
    

    Symptom: Changes not reflected in config() or env() calls.

  3. Wildcard Overreach: Wildcards in allowed (e.g., FEATURE_*) may accidentally permit sensitive variables. Explicitly list critical variables:

    'allowed' => [
        'FEATURE_NEW_CHECKOUT',
        'FEATURE_EXPERIMENTAL_API',
    ],
    
  4. 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
    
  5. 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');
    }
    

Debugging

  1. Silent Failures: Enable verbose output to debug:

    php artisan set:env APP_DEBUG=true --verbose
    

    Look for: File paths, permission checks, or validation errors.

  2. 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.

  3. File Path Issues: Customize the .env file path in config:

    'file' => base_path('.env.local'), // Use a separate file for dynamic vars
    

Tips

  1. 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')),
    
  2. 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.");
        }
    }
    
  3. Git Ignore: Add backup files to .gitignore:

    # .gitignore
    .env.backup*
    
  4. 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
    
  5. 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]);
    
  6. Security:

    • Never use this package for secrets (passwords, API keys). Use Laravel Forge, Vault, or AWS Secrets Manager instead.
    • Restrict Artisan command access in production:
      // app/Console/Kernel
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony