How to set .env values in laravel programmatically on the fly

How to set .env values in laravel programmatically on the fly

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Why Writing to .env Directly is a Bad Idea

Modifying the .env file directly from within your application logic, such as inside a controller after a user submits a form via a GUI, is fundamentally an architectural anti-pattern. While your intention—to allow users to configure database credentials or mailer settings dynamically—is valid for a custom CMS, achieving this by writing plaintext strings to the .env file breaks Laravel's core assumption regarding environment separation.

Laravel loads the contents of the .env file into the environment variables array during the bootstrap process, typically before your application kernel starts processing requests. Once you are inside a controller or service, the environment is already loaded in memory. Writing to that file at runtime does not automatically update the variable available to your current request cycle unless you manually reload it, and even then, the change persists only until the next server restart or the next time the application reads the file (which rarely happens automatically).

Furthermore, allowing a controller to write arbitrary values to .env opens a significant security vulnerability. If a user can submit sensitive database credentials through your GUI, they are effectively able to overwrite these secrets on the server disk. While you might validate the input in the controller, this approach conflates application logic with infrastructure management. It treats configuration as mutable state managed by the app rather than immutable facts provided by the environment.

The Proper Approach: Configuration Classes

The robust way to handle dynamic configuration in Laravel is to decouple the data from the file system and store it in a dedicated configuration array or class. This allows you to validate, sanitize, and persist user changes without touching the sensitive .env file directly.

You can create a new config file, for example, config/cms_settings.php. In this file, define the structure of your CMS settings:

return [
    'database' => [
        'host' => env('CMS_DB_HOST', 'localhost'),
        'port' => env('CMS_DB_PORT', 3306),
        'name' => env('CMS_DB_NAME', 'default_db'),
        'username' => env('CMS_DB_USER', 'root'),
        'password' => env('CMS_DB_PASS', ''),
    ],
    'mailer' => [
        'driver' => env('MAIL_DRIVER', 'smtp'),
        'host' => env('MAIL_HOST', 'mail.example.com'),
        'port' => env('MAIL_PORT', 587),
    ],
];

When your user submits the form via your GUI, your controller should receive the sanitized values (perhaps after passing them through a validator) and store them. Instead of writing to .env, you can either:

  1. Store in a Database: If this is a multi-tenant CMS where different clients need different settings, the most scalable solution is to store these configuration values in your database. Your application then reads from the database rather than the environment file.
  2. Update via Artisan Command: If you strictly require these values to be read from .env by other external tools or scripts that don't use Laravel, you can write a dedicated Artisan command that accepts arguments and uses Symfony\Component\Console\Input\EnvAwareInputInterface capabilities to safely update the environment file. However, this should be triggered via CLI, not directly from an HTTP request without strict validation and execution context checks.

Handling External Dependencies

A critical nuance arises if you have external dependencies or deployment scripts that rely on reading the .env file directly. If you change the configuration in your code but the external script hasn't been updated to read from a database, you are stuck with a mismatch.

In such cases, the safest pattern for a self-hosted CMS is to keep the .env file as the source of truth for secrets (like API keys or database passwords) and store non-sensitive configuration parameters in the database. For sensitive data that must live in .env, you can implement a regeneration strategy:

After validating the user's input, your controller could generate a new .env file programmatically using Laravel's helper functions, but this should be done with extreme caution. You would read existing values, merge them with the new ones from the request, and write the entire contents back to the file. This ensures consistency, preventing partial updates that might leave the environment in an inconsistent state.

use Illuminate\Support\Facades\File;
use Symfony\Component\Process\Process;

$envContent = File::get('.env');
$newEnvContent = $envContent . PHP_EOL . "# CMS Generated Overrides" . PHP_EOL;
$newEnvContent .= "CMS_DB_HOST=" . $request->input('db_host') . PHP_EOL;
$newEnvContent .= "CMS_DB_NAME=" . $request->input('db_name') . PHP_EOL;

File::put('.env', $newEnvContent);

// Note: You must restart the server or run a specific artisan command 
// to pick up these changes immediately without a reboot.

This approach is risky and generally discouraged for production environments unless you have a strict CI/CD pipeline that handles the restart automatically. Ideally, your application should be refactored to read from a central config store (database or Redis) rather than relying on the file system for runtime configuration changes.

Conclusion

While it is technically possible to write values to the .env file from a controller, doing so introduces security risks and architectural fragility. The best practice for a custom CMS is to separate sensitive secrets (which stay in .env) from dynamic application settings (which live in a database or a dedicated config array). This separation ensures that your application remains secure, scalable, and decoupled from the specific file system state of the server.

Our network