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.
Installation:
composer require syamsoul/laravel-set-env
Ensure your project uses Laravel 10.x+ and PHP 8.0+.
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');
CLI Alternative: Use the Artisan command for quick adjustments:
php artisan souldoit:set-env "APP_DEBUG=false" --force
SoulDoit\SetEnv\Facades\Env for programmatic access.souldoit:set-env for CLI workflows..env file structure after modifications (e.g., comments, variable ordering).Dynamic Configuration:
.env variables during deployment or runtime (e.g., feature flags, environment-specific settings).if (auth()->user()->isAdmin()) {
Env::set('ENABLE_ADMIN_DASHBOARD', true);
}
Environment-Specific Files:
.env.example or custom files for development/staging:
Env::envFile('.env.staging')->set('APP_URL', 'https://staging.example.com');
Positioning Variables:
.env file structure by placing variables after a key:
Env::set('DB_PASSWORD', 'secure123', afterKey: 'DB_HOST');
Result:
DB_HOST=localhost
DB_PASSWORD=secure123
Batch Updates:
php artisan souldoit:set-env "APP_ENV=production" "APP_DEBUG=false" --force
Deployment Workflow:
.env variables via a script:
// deploy.php
Env::set('APP_ENV', 'production');
Env::set('CACHE_DRIVER', 'redis');
php artisan souldoit:set-env "APP_ENV=production" --force
Local Development:
.env.example with local overrides:
php artisan souldoit:set-env "DB_DATABASE=laravel_local" -E .env.example
Feature Toggles:
if (request()->has('enable_new_ui')) {
Env::set('ENABLE_NEW_UI', true);
}
Service Providers:
AppServiceProvider for global access:
public function boot()
{
if ($this->app->environment('local')) {
Env::set('APP_DEBUG', true);
}
}
Middleware:
.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);
}
Testing:
.env variables between tests:
public function tearDown(): void
{
Env::set('TEST_VAR', null); // Remove variable
parent::tearDown();
}
Validation:
.env changes are safe:
$validator = Validator::make(['key' => 'APP_DEBUG'], [
'key' => 'required|in:APP_DEBUG,APP_ENV',
]);
File Permissions:
.env file is writable by the web server/user running Laravel:
chmod 644 .env
Permission denied when using Env::set().Variable Serialization:
// ❌ Avoid (may serialize as "1" or "0")
Env::set('ENABLE_FEATURE', true);
// ✅ Better
Env::set('ENABLE_FEATURE', 'true');
Comments in .env:
// Before:
// APP_NAME=MyApp # Old comment
Env::set('APP_NAME', 'NewApp'); // ❌ Loses comment
Env::set('APP_NAME', 'NewApp', 'Updated name'); // ✅ Keeps comment
Production Safety:
--force flag bypasses confirmation prompts. Use cautiously:
php artisan souldoit:set-env "APP_KEY=..." --force # ⚠️ Risky in prod
env() helper).Laravel Caching:
.env require clearing config cache:
php artisan config:clear
Env::set('KEY', 'VALUE');
Artisan::call('config:clear');
Multiple Files:
.env.example won’t affect .env. Use envFile() explicitly:
Env::envFile('.env.example')->set('KEY', 'VALUE');
Silent Failures:
$result = Env::set('KEY', 'VALUE');
if (!$result) {
// Handle failure (e.g., file not found)
}
Artisan Errors:
--verbose for debug output:
php artisan souldoit:set-env "KEY=VALUE" --verbose
File Locking:
.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'));
Custom File Paths:
.env path in config:
// config/set-env.php
'paths' => [
base_path('.env.custom'),
],
Pre/Post-Set Hooks:
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
});
});
}
Validation Rules:
.env keys/values:
Env::set('DB_PASSWORD', 'value', null, function ($value) {
return strlen($value) >= 12 || throw new \InvalidArgumentException('Password too weak.');
});
Backup Mechanism:
.env before modifications:
$backup = copy('.env', '.env.backup');
Env::set('KEY', 'VALUE');
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
Special Characters:
Env::set('APP_DESCRIPTION', 'My App "Quotes"');
Boolean Values:
Env::set('ENABLE_FEATURE', 'true'); // ✅ Explicit
Env::set('ENABLE_FEATURE', true); // ⚠
How can I help you explore Laravel packages today?