Use Config Caching to Speed Up Your Laravel App

Image for post
Image for post

As web developers, we’re always looking for ways to speed up our app. It’s all about milliseconds today. There are several ways by which a web app or a web service could be optimised for speed. Being one of the most used and popular PHP frameworks, Laravel has a few tricks up its sleeves to make this happen. One of them is config caching. Obviously, this is not going to make tremendous improvement, but significant enough to be written about. So what is config caching?

Well, it’s exactly what it sounds like, you cache all your configuration so that you don’t have to go looking for it every time you want to read a configuration. Laravel, as usual, has an artisan command for this:

php artisan config:cache

What does this command do? It’s common to have all sensitive configuration (such as access keys and access secrets) in the .env file in a Laravel app. These values are then read in a config file, which will then be used in the code. So the config:cache command takes all the configuration files in a project and merges them into a couple of files. These two files, config.php and services.php, are then placed in the app/bootstrap/cache/ directory. You can go in there and check how these files are generated.

There’s one thing to note here. After you use this command, the framework will bypass the env helper when you are requesting a config variable, i.e., it’ll skip the whole dotenv package. So you’ll have to change the way you read config variables. For example:

// You read from .env like this 
env('GOOGLE_API_KEY');
// But now, you'll have to change it to this config('services.google_api_key');

One more thing, it’s recommended that you cache your config only in production, because the config might change very frequently in the dev env. So the best practice is to regenerate the cache in the production env as a part of your deployment process. Every time you deploy a new release to production, you can regenerate the cache so that you always have the latest config in cache.

Coding, machine learning, reading, sleeping, listening, potato. https://blog.contactsunny.com and https://www.linkedin.com/in/sunnysrinidhi/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store