How to Use Laravel Config Files

Use Laravel configuration files to keep settings out of your main application code.

You discover that storing files on your own server is extra load, so not ideal. You open your web browser and do a google search on “efficient ways to store files”. Finally, you decide to use Amazon S3. Since you are a Laravel user, you open config/filesystems.php, and then you change the default key value from local to s3, fill in your API keys. Just like that, you have your files uploaded to Amazon S3.

Magic, no. This is an example of a configurable system, and an example of SOLID programming. By setting some array values in a file, we can get a system to work without breaking anything. This article is not about SOLID, we are here to talk about Laravel configuration files and how to use them.

Configuration files in Laravel provide an easy way to set options required by parts of our application to work. Laravel has a lot of configuration files in the config directory. We as developers also have the option to create our own configuration file(s).

When to use Config file

When building a Laravel Package, config files go a long way in helping you build a configurable and functional package.

Creating a Configuration File

One reason developers love Laravel is the fact that it makes everything simple. Creating configuration files is not an exception to that rule. To create a configuration file, go to the config directory and create a file there. For our example, let’s call our file social.php. After creating the file, open it and return an empty array. There, we have created a configuration file.

return [];

Adding Options

Now that we have our config file, we need to set options. To do that, we set array key values as our options.

return [ 'facebook' => 'https://www.facebook.com/scotchdevelopment', 'twitter' => 'https://twitter.com/scotch_io' ];

We can even use multi-dimensional arrays too.

return [ 'facebook' => [ 'url' => 'https://www.facebook.com/scotchdevelopment', 'username' => 'scotchdevelopment' ], 'twitter' => [ 'url' => 'https://twitter.com/scotch_io', 'username' => 'scotch_io' ] ];

Using Config Variables


Originally published at www.laravelfeed.com.