Use Config Caching to Speed Up Your Laravel App

Sunny Srinidhi

--

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Sunny Srinidhi
Sunny Srinidhi

No responses yet

Write a response