Skip to main content

Laravel Env Modifier Showcase

Discover real-world examples and use cases of Laravel Env Modifier in action. See how different applications leverage programmatic .env file management to automate deployments, manage multiple environments, and streamline configuration workflows.

Understanding Env Modifier Components

Laravel Env Modifier provides powerful features for managing .env files:

  • File Operations: Create, backup, restore, delete, and merge .env files
  • Key Operations: Read, write, rename, delete, and check existence of keys
  • Value Normalization: Automatic handling of booleans, arrays, JSON, and special characters
  • Atomic Writes: Exclusive locks prevent race conditions
  • Comment Preservation: Maintains file structure and comments

Deployment Automation

Automated Environment Setup

Automate environment configuration during deployment

Overview

Deployment scripts often need to configure environment variables based on the target environment (staging, production, etc.). Laravel Env Modifier enables you to automate this process by creating environment-specific files, merging configurations from templates, and setting environment-specific values programmatically.

Deployment Features
  • Environment-specific files
  • Template-based configuration
  • Automatic value updates
  • Backup before changes
  • Rollback capability
  • Multi-environment support
Business Benefits
  • Faster deployments
  • Reduced human error
  • Consistent configurations
  • Automated workflows
  • Easy rollback
  • Version control friendly

Implementation Example

namespace App\Services;

use JobMetric\EnvModifier\Facades\EnvModifier as EnvMod;

class DeploymentService
{
public function setupEnvironment(string $environment): void
{
$envFile = base_path(".env.{$environment}");

// Create backup of existing file if it exists
if (file_exists($envFile)) {
EnvMod::setPath($envFile);
EnvMod::backup('.pre-deploy');
}

// Create or bind to environment file
if (!file_exists($envFile)) {
EnvMod::createFile($envFile, [], bindToPath: true);
} else {
EnvMod::setPath($envFile);
}

// Merge base configuration
EnvMod::mergeFromPath(base_path('.env.template'), except: ['APP_KEY']);

// Set environment-specific values
$config = $this->getEnvironmentConfig($environment);
EnvMod::set([
'APP_ENV' => $environment,
'APP_DEBUG' => $config['debug'],
'APP_URL' => $config['url'],
'DB_CONNECTION' => $config['database']['connection'],
'DB_HOST' => $config['database']['host'],
'DB_DATABASE' => $config['database']['database'],
'CACHE_DRIVER' => $config['cache'],
'SESSION_DRIVER' => $config['session'],
]);

// Set defaults if missing
EnvMod::setIfMissing([
'APP_TIMEZONE' => 'UTC',
'LOG_CHANNEL' => 'stack',
]);
}

private function getEnvironmentConfig(string $environment): array
{
return match($environment) {
'production' => [
'debug' => false,
'url' => 'https://example.com',
'database' => [
'connection' => 'mysql',
'host' => 'prod-db.example.com',
'database' => 'production_db',
],
'cache' => 'redis',
'session' => 'redis',
],
'staging' => [
'debug' => false,
'url' => 'https://staging.example.com',
'database' => [
'connection' => 'mysql',
'host' => 'staging-db.example.com',
'database' => 'staging_db',
],
'cache' => 'file',
'session' => 'file',
],
default => [
'debug' => true,
'url' => 'http://localhost',
'database' => [
'connection' => 'mysql',
'host' => '127.0.0.1',
'database' => 'local_db',
],
'cache' => 'file',
'session' => 'file',
],
};
}
}

Multi-Environment Management

Environment Configuration Manager

Manage multiple environment configurations efficiently

Overview

Applications often need to manage multiple environment configurations (development, staging, production, testing). Laravel Env Modifier makes it easy to create, update, and synchronize configurations across different environments while maintaining a base template and environment-specific overrides.

Management Features
  • Template-based setup
  • Environment-specific overrides
  • Configuration synchronization
  • Key migration between environments
  • Bulk updates
  • Configuration validation
Business Benefits
  • Consistent configurations
  • Easy environment setup
  • Reduced configuration drift
  • Faster onboarding
  • Better organization
  • Version control integration

Implementation Example

namespace App\Services;

use JobMetric\EnvModifier\Facades\EnvModifier as EnvMod;

class EnvironmentManager
{
public function syncConfiguration(string $fromEnv, string $toEnv, array $keys = []): void
{
$fromFile = base_path(".env.{$fromEnv}");
$toFile = base_path(".env.{$toEnv}");

// Ensure target file exists
if (!file_exists($toFile)) {
EnvMod::createFile($toFile, [], bindToPath: true);
} else {
EnvMod::setPath($toFile);
}

// Merge selected keys from source
if (empty($keys)) {
// Sync all keys except sensitive ones
EnvMod::mergeFromPath($fromFile, except: ['APP_KEY', 'DB_PASSWORD']);
} else {
// Sync only specified keys
EnvMod::mergeFromPath($fromFile, only: $keys);
}
}

public function updateKeyAcrossEnvironments(array $environments, string $key, mixed $value): void
{
foreach ($environments as $env) {
$envFile = base_path(".env.{$env}");

if (!file_exists($envFile)) {
continue;
}

EnvMod::setPath($envFile);
EnvMod::set([$key => $value]);
}
}

public function migrateKey(string $oldKey, string $newKey, array $environments): void
{
foreach ($environments as $env) {
$envFile = base_path(".env.{$env}");

if (!file_exists($envFile)) {
continue;
}

EnvMod::setPath($envFile);

if (EnvMod::has($oldKey) && !EnvMod::has($newKey)) {
EnvMod::rename($oldKey, $newKey);
}
}
}

public function createEnvironmentFromTemplate(string $environment, array $overrides = []): void
{
$envFile = base_path(".env.{$environment}");

// Create from template
EnvMod::createFile($envFile, [], bindToPath: true);
EnvMod::mergeFromPath(base_path('.env.template'), except: ['APP_KEY']);

// Apply environment-specific overrides
if (!empty($overrides)) {
EnvMod::set($overrides);
}

// Set environment name
EnvMod::set(['APP_ENV' => $environment]);
}
}

Configuration Migration

Safe Key Refactoring

Migrate and refactor configuration keys safely

Overview

As applications evolve, configuration keys may need to be renamed or restructured. Laravel Env Modifier provides safe mechanisms to migrate keys, ensuring no data is lost and allowing for rollback if needed. This is particularly useful when deprecating old keys or standardizing naming conventions.

Migration Features
  • Key renaming
  • Bulk migrations
  • Backup before changes
  • Rollback capability
  • Validation checks
  • Multi-file support
Business Benefits
  • Safe refactoring
  • No data loss
  • Easy rollback
  • Consistent naming
  • Automated migrations
  • Reduced risk

Implementation Example

namespace App\Services;

use JobMetric\EnvModifier\Facades\EnvModifier as EnvMod;

class ConfigurationMigrationService
{
public function migrateLegacyKeys(array $migrations): void
{
$envFile = base_path('.env');

// Create backup before migration
EnvMod::setPath($envFile);
$backup = EnvMod::backup('.pre-migration');

try {
foreach ($migrations as $oldKey => $newKey) {
if (EnvMod::has($oldKey) && !EnvMod::has($newKey)) {
EnvMod::rename($oldKey, $newKey, overwrite: false);
} elseif (EnvMod::has($oldKey) && EnvMod::has($newKey)) {
// Both exist - log conflict
\Log::warning("Migration conflict: Both {$oldKey} and {$newKey} exist");
}
}
} catch (\Exception $e) {
// Restore backup on error
EnvMod::restore($backup);
throw $e;
}
}

public function deprecateKeys(array $keys): void
{
$envFile = base_path('.env');
EnvMod::setPath($envFile);

foreach ($keys as $key) {
if (EnvMod::has($key)) {
// Rename to deprecated prefix
$deprecatedKey = "DEPRECATED_{$key}";
EnvMod::rename($key, $deprecatedKey, overwrite: false);

\Log::info("Deprecated key: {$key} -> {$deprecatedKey}");
}
}
}

public function standardizeNaming(array $patterns): void
{
$envFile = base_path('.env');
EnvMod::setPath($envFile);
$all = EnvMod::all();

$backup = EnvMod::backup('.pre-standardize');

try {
foreach ($all as $key => $value) {
foreach ($patterns as $pattern => $replacement) {
if (preg_match($pattern, $key, $matches)) {
$newKey = preg_replace($pattern, $replacement, $key);

if ($newKey !== $key && !EnvMod::has($newKey)) {
EnvMod::rename($key, $newKey);
}
}
}
}
} catch (\Exception $e) {
EnvMod::restore($backup);
throw $e;
}
}
}