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

Dotenv Editor Laravel Package

atournayre/dotenv-editor

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require atournayre/dotenv-editor
    

    (Note: Due to archival status, verify compatibility with your Laravel version.)

  2. Basic Usage: Load the .env file in your Laravel app:

    use DotenvEditor\DotenvEditor;
    
    $editor = new DotenvEditor();
    $editor->load('.env'); // Loads .env file into memory
    
  3. First Use Case: Update a single key dynamically (e.g., in a config panel):

    $editor->set('APP_DEBUG', 'true');
    $editor->save(); // Persists changes to .env
    
  4. Laravel Integration: Use with Laravel’s env() helper:

    $value = $editor->get('APP_DEBUG'); // Returns 'true' if set
    

Implementation Patterns

Workflows

  1. Dynamic Configuration:

    • Use in admin panels to edit .env values without redeploying:
      $editor->set('MAIL_MAILER', 'smtp');
      $editor->save();
      
  2. Environment-Specific Edits:

    • Load and modify .env.local or .env.production:
      $editor->load('.env.local');
      $editor->set('DB_PASSWORD', 'new_secure_password');
      $editor->save();
      
  3. Validation Before Save:

    • Validate keys/values before persisting:
      if ($editor->validateKey('APP_URL', 'https://example.com')) {
          $editor->save();
      }
      

Integration Tips

  • Service Provider: Bind the editor to Laravel’s container for dependency injection:

    $this->app->singleton(DotenvEditor::class, function ($app) {
        return new DotenvEditor();
    });
    
  • Middleware: Restrict .env edits to admin users:

    public function handle($request, Closure $next) {
        if (!$request->user()->isAdmin()) {
            abort(403);
        }
        return $next($request);
    }
    
  • Form Requests: Use in Laravel’s FormRequest for safe updates:

    public function rules() {
        return ['key' => 'required|alpha_dash', 'value' => 'required'];
    }
    
    public function updateEnv(DotenvEditor $editor) {
        $editor->set($this->key, $this->value);
        $editor->save();
    }
    

Gotchas and Tips

Pitfalls

  1. File Permissions:

    • Ensure .env files are writable by the web server user:
      chmod 644 .env
      
    • Gotcha: PHP may fail silently if permissions are incorrect.
  2. Key Validation:

    • The package lacks built-in validation for key formats (e.g., ALLOWED_KEYS).
    • Fix: Add regex validation:
      if (!preg_match('/^[A-Z_]+$/', $key)) {
          throw new \InvalidArgumentException('Invalid key format.');
      }
      
  3. Environment Overrides:

    • Changes to .env may not reflect immediately in env() due to Laravel’s caching.
    • Fix: Clear config cache after edits:
      Artisan::call('config:clear');
      
  4. Archived Package:

    • No active maintenance; test thoroughly in staging.
    • Alternative: Consider vlucas/phpdotenv for modern use cases.

Debugging

  • Check Loaded Values:

    print_r($editor->getAll()); // Debug current .env state
    
  • Silent Failures: Wrap operations in try-catch:

    try {
        $editor->save();
    } catch (\Exception $e) {
        Log::error('Dotenv save failed: ' . $e->getMessage());
    }
    

Extension Points

  1. Custom Storage: Override save() to log changes or encrypt values:

    public function save() {
        $this->logChange('APP_DEBUG', $this->data['APP_DEBUG']);
        parent::save();
    }
    
  2. Key Whitelisting: Extend the class to restrict editable keys:

    protected $allowedKeys = ['APP_DEBUG', 'APP_ENV'];
    
    public function set($key, $value) {
        if (!in_array($key, $allowedKeys)) {
            throw new \RuntimeException("Key '$key' is not editable.");
        }
        $this->data[$key] = $value;
    }
    
  3. Backup Mechanism: Add pre-save backup:

    public function save() {
        copy('.env', '.env.backup');
        parent::save();
    }
    
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium