Installation:
composer require atournayre/dotenv-editor
(Note: Due to archival status, verify compatibility with your Laravel version.)
Basic Usage:
Load the .env file in your Laravel app:
use DotenvEditor\DotenvEditor;
$editor = new DotenvEditor();
$editor->load('.env'); // Loads .env file into memory
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
Laravel Integration:
Use with Laravel’s env() helper:
$value = $editor->get('APP_DEBUG'); // Returns 'true' if set
Dynamic Configuration:
.env values without redeploying:
$editor->set('MAIL_MAILER', 'smtp');
$editor->save();
Environment-Specific Edits:
.env.local or .env.production:
$editor->load('.env.local');
$editor->set('DB_PASSWORD', 'new_secure_password');
$editor->save();
Validation Before Save:
if ($editor->validateKey('APP_URL', 'https://example.com')) {
$editor->save();
}
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();
}
File Permissions:
.env files are writable by the web server user:
chmod 644 .env
Key Validation:
ALLOWED_KEYS).if (!preg_match('/^[A-Z_]+$/', $key)) {
throw new \InvalidArgumentException('Invalid key format.');
}
Environment Overrides:
.env may not reflect immediately in env() due to Laravel’s caching.Artisan::call('config:clear');
Archived Package:
vlucas/phpdotenv for modern use cases.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());
}
Custom Storage:
Override save() to log changes or encrypt values:
public function save() {
$this->logChange('APP_DEBUG', $this->data['APP_DEBUG']);
parent::save();
}
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;
}
Backup Mechanism: Add pre-save backup:
public function save() {
copy('.env', '.env.backup');
parent::save();
}
How can I help you explore Laravel packages today?