{{announcement.body}}
{{announcement.title}}

How to Load Custom JSON Files Into Laravel's Config

DZone 's Guide to

How to Load Custom JSON Files Into Laravel's Config

Working with a large config file can be annoying. I wanted to share my solution to loading custom settings from a JSON file into Laravel’s config.

· Web Dev Zone ·
Free Resource

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? I was working on 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.

Loading the Settings file

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, I add it to the app config. Now, you are able to access all the keys from the settings file as config('settings.name') or whatever the key is.

Loading the settings file

Writing the Settings File

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.

Writing the settings file

Conclusion

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

Thank You
That’s all for now, this has been Adi.
If you are looking for a Freelance Web Developer you can contact me

Topics:
config, file, laravel, php, tutorial

Published at DZone with permission of Adi Sk . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}