How to edit and save custom config files in Laravel?

前端 未结 4 650
鱼传尺愫
鱼传尺愫 2021-02-04 16:47

I am creating simple web application in Laravel 4. I have backend for managing applications content. As a part of backend i want to have UI to manage applications settings. I wa

相关标签:
4条回答
  • 2021-02-04 17:02

    Based upon @Batman answer with respect to current version (from 5.1 to 6.x):

    config(['YOUR-CONFIG.YOUR_KEY' => 'NEW_VALUE']);
    $text = '<?php return ' . var_export(config('YOUR-CONFIG'), true) . ';';
    file_put_contents(config_path('YOUR-CONFIG.php'), $text);
    
    0 讨论(0)
  • 2021-02-04 17:04

    Afiak there is no built-in functionality for manipulating config files. I see 2 options to achieve this:

    • You can store your custom config in your database and override the default config at runtime with Config::set('key', 'value'); But be aware that

    Configuration values that are set at run-time are only set for the current request, and will not be carried over to subsequent requests. @see: http://laravel.com/docs/configuration

    • Since config files are simple php arrays, it's easy to read, manipulate and write them. So with a little custom code this should be done quickly.

    In general I'd prefer the first option. Overriding config files can might cause some troubles when it comes to version control, deployment, automated testing, etc. But as always, this strongly depends on your project setup.

    0 讨论(0)
  • 2021-02-04 17:06

    I did it like this ...

    config(['YOURKONFIG.YOURKEY' => 'NEW_VALUE']);
    $fp = fopen(base_path() .'/config/YOURKONFIG.php' , 'w');
    fwrite($fp, '<?php return ' . var_export(config('YOURKONFIG'), true) . ';');
    fclose($fp);
    
    0 讨论(0)
  • 2021-02-04 17:19

    You'll have to extend the Fileloader, but it's very simple:

    class FileLoader extends \Illuminate\Config\FileLoader
    {
        public function save($items, $environment, $group, $namespace = null)
        {
            $path = $this->getPath($namespace);
    
            if (is_null($path))
            {
                return;
            }
    
            $file = (!$environment || ($environment == 'production'))
                ? "{$path}/{$group}.php"
                : "{$path}/{$environment}/{$group}.php";
    
            $this->files->put($file, '<?php return ' . var_export($items, true) . ';');
        }
    }
    

    Usage:

    $l = new FileLoader(
        new Illuminate\Filesystem\Filesystem(), 
        base_path().'/config'
    );
    
    $conf = ['mykey' => 'thevalue'];
    
    $l->save($conf, '', 'customconfig');
    
    0 讨论(0)
提交回复
热议问题