Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to change variables in the .env file dynamically in Laravel?
In Laravel, the .env file contains environment variables that configure your application's behavior across different environments (local, staging, production). While these variables are typically static, you can modify them dynamically using PHP file operations.
Understanding the .env File
The .env file contains key-value pairs for configuration
APP_NAME=Laravel APP_ENV=local APP_KEY=base64:BUdhVZjOEzjFihHKgt1Cc+gkQKPoA4iH98p5JwcuNho= APP_DEBUG=true APP_URL=http://localhost DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=test DB_USERNAME=root DB_PASSWORD=
These variables are used throughout Laravel's configuration files in the config/ folder and should not be committed to version control as they vary per environment.
Fetching Current Environment
You can retrieve the current environment using Laravel's App facade
<?php use Illuminate\Support\Facades\App; $environment = App::environment(); echo $environment; ?>
local
Reading Environment Variables
Use the env() helper function to fetch specific environment values
<?php
echo env('APP_URL');
echo "<br/>";
echo env('APP_ENV');
echo "<br/>";
echo env('DB_DATABASE');
?>
http://localhost local test
Changing Environment Variables Dynamically
To modify .env variables at runtime, read the file, replace values, and write back
<?php
$path = base_path('.env');
$envContent = file_get_contents($path);
if (file_exists($path)) {
$newContent = str_replace(
'APP_ENV=local',
'APP_ENV=production',
$envContent
);
file_put_contents($path, $newContent);
echo "Environment changed to production";
}
?>
Alternative Method Using $_ENV
Access all environment variables using the global $_ENV array
<?php print_r($_ENV); ?>
Array( [APP_NAME] => Laravel [APP_ENV] => local [APP_DEBUG] => true [DB_CONNECTION] => mysql [DB_HOST] => 127.0.0.1 ... )
Key Points
- Changes to .env require application restart in production
- Use
escapeshellarg()when handling user input for security - Consider using Laravel's config cache in production environments
Conclusion
Dynamic environment variable changes in Laravel require file manipulation using file_get_contents() and str_replace(). Always validate changes and restart your application to ensure new values take effect.
