Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

php - Laravel dynamic config settings

I'm using a package within my project and it stores a setting inside config/packagename

I would like to dynamically change this value inside the config file, this is how the file structure looks currently;

<?php

return [
    'view_id' => '118754561',

    'cache_lifetime_in_minutes' => 60 * 24,
];

I would like to change it to something like this -

'view_id' => Auth::user()->id,

Can you do this within the config file, or do you have to store some sort of variable to be updated later within a controller. Is there a way to place these variables in an env file and access these new variables from a controller?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This also is a generic solution to dynamically update your .env file (respective the individual key/value pairs)

  1. Change the setting in your config/packagename like so:
return [
    'view_id' => env('VIEW_ID', '118754561'),
    etc...
]
  1. Add an initial value into .env:

    VIEW_ID=118754561

  2. In an appropriate controller (e.g. AuthController), use the code below and call the function like this: updateDotEnv('VIEW_ID', Auth::User()->id)

    protected function updateDotEnv($key, $newValue, $delim='')
    {
    
        $path = base_path('.env');
        // get old value from current env
        $oldValue = env($key);
    
        // was there any change?
        if ($oldValue === $newValue) {
            return;
        }
    
        // rewrite file content with changed data
        if (file_exists($path)) {
            // replace current value with new value 
            file_put_contents(
                $path, str_replace(
                    $key.'='.$delim.$oldValue.$delim, 
                    $key.'='.$delim.$newValue.$delim, 
                    file_get_contents($path)
                )
            );
        }
    }
    

(The $delim parameter is needed if you want to make this function more generic in order to work with key=value pairs in .env where the value has to be enclosed in double quotes because they contain spaces).

Admittedly, this might not be a good solution if you have multiple users at the same time using this package in your project. So it depends on what you are using this package for.

NB: You need to make the function public of course if you plan to use it from other classes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...