Hi All, this is Adi, again with another Laravel blog post. This time I wanted to share my solution to loading custom settings from a JSON file into Laravel’s config. Firstly what’s the use case for this, there was a client project, where they had a huge list of configurations in a JSON file and I had to use them in the code. An ideal solution for this could be storing these settings in the database and query them on demand, but I was not able to persuade them to this option, so here’s my solution to how I did it.
First, let’s see how to load this file when the app initializes.
In the code below I load the
settings.json that's in the
storage folder in my
AppServiceProvider's boot method. But if you have a lot more logic happening in your service provider you can create a new one just for this purpose.
I check if the file exists, if so, I decode the JSON into a PHP
array then add it to the app config. Now you are able to access all the key's from the settings file as
config('settings.name') or whatever the key is.
Now let's see how to edit or write to this file when you need to make new changes to the config.
In the below code, I show an example of getting the whole settings file's contents and saving it to the file. But you can customize this for your own need, let's say you just need to edit one property, you can do this by updating your config like so
config(['settings.name' => 'New Value']) and you could
json_encode(config('settings')) and save the results to the file system.
I hope this gives you some idea of how to handle JSON config files in your Laravel app. The code example I gave you might be basic but you can extend this to your own needs. Be cautious since you're reading and writing to the file system directly.
For more Laravel resources visit BestOfLaravel.com
That's all for now, this has been Adi.
If you are looking for a Freelance Web Developer you can contact me