How to change variables in the .env file dynamically in Laravel?
There is no built in way to do that. If you really want to change the contents of the .env
file, you'll have to use some kind of string replace in combination with PHP's file writing methods. For some inspiration, you should take a look at the key:generate
command: KeyGenerateCommand.php:
$path = base_path('.env');
if (file_exists($path)) {
file_put_contents($path, str_replace(
'APP_KEY='.$this->laravel['config']['app.key'], 'APP_KEY='.$key, file_get_contents($path)
));
}
After the file path is built and the existence is checked, the command simply replaces APP_KEY=[current app key]
with APP_KEY=[new app key]
. You should be able to do the same string replacement with other variables.
Last but not least I just wanted to say that it might isn't the best idea to let users change the .env file. For most custom settings I would recommend storing them in the database, however this is obviously a problem if the setting itself is necessary to connect to the database.
How to change php dotenv (.env) variables dynamically in laravel or php?
putenv() work like a charm :
echo env('APP_ENV');
putenv('APP_ENV=testing');
echo env('APP_ENV');
Output:
staging
testing
.env file is unattached ...
Laravel 5.2 dynamic environment variables based on user
Yes it is possible, but not in the .env
file. Instead, you can move your logic to middleware:
Step 1: Add default values to the application config
Open your app/config/app.php
and add your default values to the existing array.
<?php
return [
'APP_ID' => '45678',
'APP_SECRET' => 'abc456',
...
];
Step 2: Create a new Middleware
php artisan make:middleware SetAppConfigForUserMiddleware
Edit the file to look like this:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
class SetAppConfigForUserMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$authorizedUser = Auth::user();
if (!App::runningInConsole() && !is_null($authorizedUser)) {
Config::set('app.APP_ID', 'appidOfUser' . $authorizedUser->name);
Config::set('app.APP_SECRET', 'appsecretOfUser' . $authorizedUser->email);
}
return $next($request);
}
}
Step 4: Run your middleware
If you need to set this config for the user in all the web routes you can add to the $middlewareGroups
array in app/Http/kernel.php
. This will apply the middleware to all the routes inside web.php
.
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
...
\App\Http\Middleware\SetAppConfigForUserMiddleware::class,
],
Step 5: Testing
For example, my Auth:user()->name
is "John" and my Auth:user()->email
is "john@example.com"
If you put this in your resources/views/home.blade.php
App Id Of User <code>{{config('app.APP_ID')}}</code>
App Secret Of User <code>{{config('app.APP_SECRET')}}</code>
The result will be appidOfUserJohn
and appsecretOfUserjohn@example.com
.
Dynamically merge .env file old key value in Laravel 5.7
Whenever you change the .env file, you need to refresh the Laravel configuration cache by php artisan config:cache
.
So your function will become:
use Illuminate\Support\Facades\Artisan;
private function setEnv($key, $value)
{
$path = base_path('.env');
if (file_exists($path)) {
// Get all the lines from that file
$lines = explode("\n", file_get_contents($path));
$settings = collect($lines)
->filter() // remove empty lines
->transform(function ($item) {
return explode("=", $item, 2);
}) // separate key and values
->pluck(1, 0); // keys to keys, values to values
$settings[$key] = $value; // set the new value whether it exists or not
$rebuilt = $settings->map(function ($value, $key) {
return "$key=$value";
})->implode("\n"); // rebuild the env file
file_put_contents($path, $rebuilt); // put the new contents
Artisan::call("config:cache"); // cache the added/modified parameter
}
}
How to change environment values dynamically
You can utilize the Config
facade to change values at runtime. For example:
Config::set('app.timezone', 'America/Chicago');
At the end of the request, that value is no longer set.
You can also use the config()
helper method and pass it an array so it knows it needs to be set:
config(['app.timezone' => 'America/Chicago']);
See also: https://laravel.com/docs/5.1/#configuration
How to set .env values in laravel programmatically on the fly
Since Laravel uses config files to access and store .env
data, you can set this data on the fly with config()
method:
config(['database.connections.mysql.host' => '127.0.0.1']);
To get this data use config()
:
config('database.connections.mysql.host')
To set configuration values at runtime, pass an array to the
config
helper
https://laravel.com/docs/5.3/configuration#accessing-configuration-values
Related Topics
Laravel Migration Table Already Exists, But I Want to Add New Not the Older
What's the Difference Between Array_Merge and Array + Array
PHP Cli Getting Input from User and Then Dumping into Variable Possible
Codeigniter Activerecord, Retrieve Last Insert Id
How to Run a Cronjob Every X Minutes
Composer Update Failed -- Out of Memory
Design Patterns: How to Create Database Object/Connection Only When Needed
How to Set Cron Job Url for Codeigniter
Accessing an Associative Array by Integer Index in PHP
Getting Relative Path from Absolute Path in PHP
Phpmailer: Reply Using Only "Reply To" Address
Using MySQL Concat() in Where Clause
What's the Most Efficient Test of Whether a PHP String Ends with Another String
Access Joomla 2.5 from External Script to Get Article by Id
Filling Gaps in Dates Returned from Database - Pure SQL Solution Possible