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 Laravel Package

syamsoul/laravel-set-env

Programmatically set, update, and read Laravel .env variables with a simple facade and CLI. Supports comments, precise placement, and multiple env files (.env, .env.example). Includes production safety checks for secure environment configuration management.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require syamsoul/laravel-set-env
    

    Ensure your project uses Laravel 10.x+ and PHP 8.0+.

  2. First Use Case: Set a .env variable programmatically in a controller or service:

    use SoulDoit\SetEnv\Facades\Env;
    
    // Set a variable with a comment
    Env::set('APP_DEBUG', false, 'Disable debug mode in production');
    
    // Retrieve the value
    $debugMode = Env::get('APP_DEBUG');
    
  3. CLI Alternative: Use the Artisan command for quick adjustments:

    php artisan souldoit:set-env "APP_DEBUG=false" --force
    

Where to Look First

  • Facade API: SoulDoit\SetEnv\Facades\Env for programmatic access.
  • Artisan Command: souldoit:set-env for CLI workflows.
  • Configuration: Check .env file structure after modifications (e.g., comments, variable ordering).

Implementation Patterns

Usage Patterns

  1. Dynamic Configuration:

    • Override .env variables during deployment or runtime (e.g., feature flags, environment-specific settings).
    • Example: Toggle a feature based on user role:
      if (auth()->user()->isAdmin()) {
          Env::set('ENABLE_ADMIN_DASHBOARD', true);
      }
      
  2. Environment-Specific Files:

    • Target .env.example or custom files for development/staging:
      Env::envFile('.env.staging')->set('APP_URL', 'https://staging.example.com');
      
  3. Positioning Variables:

    • Control .env file structure by placing variables after a key:
      Env::set('DB_PASSWORD', 'secure123', afterKey: 'DB_HOST');
      
      Result:
      DB_HOST=localhost
      DB_PASSWORD=secure123
      
  4. Batch Updates:

    • Use the Artisan command for bulk changes (e.g., CI/CD pipelines):
      php artisan souldoit:set-env "APP_ENV=production" "APP_DEBUG=false" --force
      

Workflows

  1. Deployment Workflow:

    • Pre-deploy: Update .env variables via a script:
      // deploy.php
      Env::set('APP_ENV', 'production');
      Env::set('CACHE_DRIVER', 'redis');
      
    • Post-deploy: Run the Artisan command:
      php artisan souldoit:set-env "APP_ENV=production" --force
      
  2. Local Development:

    • Sync .env.example with local overrides:
      php artisan souldoit:set-env "DB_DATABASE=laravel_local" -E .env.example
      
  3. Feature Toggles:

    • Dynamically enable/disable features:
      if (request()->has('enable_new_ui')) {
          Env::set('ENABLE_NEW_UI', true);
      }
      

Integration Tips

  1. Service Providers:

    • Register the facade in AppServiceProvider for global access:
      public function boot()
      {
          if ($this->app->environment('local')) {
              Env::set('APP_DEBUG', true);
          }
      }
      
  2. Middleware:

    • Modify .env variables based on request context:
      public function handle(Request $request, Closure $next)
      {
          if ($request->ip() === 'trusted-proxy') {
              Env::set('TRUSTED_PROXIES', '*');
          }
          return $next($request);
      }
      
  3. Testing:

    • Reset .env variables between tests:
      public function tearDown(): void
      {
          Env::set('TEST_VAR', null); // Remove variable
          parent::tearDown();
      }
      
  4. Validation:

    • Combine with Laravel’s validation to ensure .env changes are safe:
      $validator = Validator::make(['key' => 'APP_DEBUG'], [
          'key' => 'required|in:APP_DEBUG,APP_ENV',
      ]);
      

Gotchas and Tips

Pitfalls

  1. File Permissions:

    • Ensure the .env file is writable by the web server/user running Laravel:
      chmod 644 .env
      
    • Error: Permission denied when using Env::set().
  2. Variable Serialization:

    • Boolean/array values may not serialize as expected. Use strings or JSON:
      // ❌ Avoid (may serialize as "1" or "0")
      Env::set('ENABLE_FEATURE', true);
      
      // ✅ Better
      Env::set('ENABLE_FEATURE', 'true');
      
  3. Comments in .env:

    • Comments are preserved but may be stripped if the variable is updated without specifying a comment:
      // Before:
      // APP_NAME=MyApp # Old comment
      Env::set('APP_NAME', 'NewApp'); // ❌ Loses comment
      Env::set('APP_NAME', 'NewApp', 'Updated name'); // ✅ Keeps comment
      
  4. Production Safety:

    • The --force flag bypasses confirmation prompts. Use cautiously:
      php artisan souldoit:set-env "APP_KEY=..." --force  # ⚠️ Risky in prod
      
    • Tip: Restrict CLI access in production or use environment variables via other means (e.g., env() helper).
  5. Laravel Caching:

    • Changes to .env require clearing config cache:
      php artisan config:clear
      
    • Automate this in a post-update hook:
      Env::set('KEY', 'VALUE');
      Artisan::call('config:clear');
      
  6. Multiple Files:

    • Modifying .env.example won’t affect .env. Use envFile() explicitly:
      Env::envFile('.env.example')->set('KEY', 'VALUE');
      

Debugging

  1. Silent Failures:

    • Check return values for errors:
      $result = Env::set('KEY', 'VALUE');
      if (!$result) {
          // Handle failure (e.g., file not found)
      }
      
  2. Artisan Errors:

    • Use --verbose for debug output:
      php artisan souldoit:set-env "KEY=VALUE" --verbose
      
  3. File Locking:

    • Avoid concurrent writes to .env. Use locks:
      if (file_exists(storage_path('framework/env.lock'))) {
          throw new \RuntimeException('Environment file is locked.');
      }
      file_put_contents(storage_path('framework/env.lock'), '');
      Env::set('KEY', 'VALUE');
      unlink(storage_path('framework/env.lock'));
      

Extension Points

  1. Custom File Paths:

    • Override the default .env path in config:
      // config/set-env.php
      'paths' => [
          base_path('.env.custom'),
      ],
      
  2. Pre/Post-Set Hooks:

    • Extend the SoulDoit\SetEnv\SetEnvServiceProvider to add logic before/after writes:
      public function boot()
      {
          Env::extend(function ($app) {
              $app->afterSet(function ($key, $value) {
                  // Log changes or trigger events
              });
          });
      }
      
  3. Validation Rules:

    • Add custom validation for .env keys/values:
      Env::set('DB_PASSWORD', 'value', null, function ($value) {
          return strlen($value) >= 12 || throw new \InvalidArgumentException('Password too weak.');
      });
      
  4. Backup Mechanism:

    • Create a backup of .env before modifications:
      $backup = copy('.env', '.env.backup');
      Env::set('KEY', 'VALUE');
      

Configuration Quirks

  1. Case Sensitivity:

    • .env keys are case-sensitive. Ensure consistency:
      Env::set('APP_DEBUG', 'true'); // Correct
      Env::set('app_debug', 'true'); // ❌ Won't match APP_DEBUG
      
  2. Special Characters:

    • Escape values with spaces/special chars:
      Env::set('APP_DESCRIPTION', 'My App "Quotes"');
      
  3. Boolean Values:

    • Use strings for clarity:
      Env::set('ENABLE_FEATURE', 'true'); // ✅ Explicit
      Env::set('ENABLE_FEATURE', true);   // ⚠
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor