I created a Laravel application with a view which is a form that contains some input fields populated by a laravel configuration file "config.options".
I want to update this file through this particular view, I am talking about a standard php file in config folder, not database stuffs.
To do this, in my controller I have an update method like this
LARAVEL PHP CONTROLLER
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
/*VarExporter is just a library to beautify parsed arrays instead of using var_export*/
use Brick\VarExporter\VarExporter;
class SettingsController extends Controller
{
public function update(Request $request){
$values = $request->validate([
"support_mail" => ['required', 'email:rfc,dns'],
"api_endpoint" => ['required','URL']
]);
$config = (object) config('options');
$config->support_mail = $request->support_mail;
$config->api_endpoint= $request->api_endpoint;
$newConfig = VarExporter::export(
(array) $config,
VarExporter::INLINE_SCALAR_LIST | VarExporter::ADD_RETURN
);
if( \File::put(base_path() . '/config/options.php', "<?php\n\n". $newConfig) ) {
\Artisan::call('config:clear');
return back()->with('message', 'Settings updated');
}
}
What I am doing here is:
- Recall the configuration as an object into $newConfig variable
- Update the requested values into $newConfig
- Write the configuration file with the new configuration
- Clear the configuration cache
- Turn back with succesfull message.
This is simply working, no doubt about this, problem is that when I turn back in the view after successfull submit, the input fields are not updated, but if I wait 2 seconds and refresh the page the configuration looks updated. So I tried to sleep 2 seconds
sleep(2);
return back()->with('message', 'Settings updated');
before returning and fields are updated, is like when I refresh the cache it takes some time to update the configuration, or at least more then the time that it takes to refresh the page.
I really tried everything but I cannot find a way out, obviosly I know that I can do this through database, but I want to understand how to do this in this way just for educational purposes. I'm supposing that I have to do a sort of loop every second to check if the configuration cache is clear and then turn back, but I cannot understand where is the configuration cache stored, because framework/cache/data looks empty
UPDATE
just to exclude something related to caching of configuration, I tried to do the same thing using an unrelated framework file, and instead of the config helper, I used require of canonical PHP language and file_put_contents. The result is exactly the same.. so I'm thinking something about the management of file system by php, I don't think is laravel related.
UPDATE 2
Ok so.. if I Log
file_get_contents(base_path() . '/config/options.php')
instead of
config('options')
after submiting, the data will be updated.. so is something related with the config helper I think