Just released! Manage your Laravel projects with Invoker. The no-bull Laravel admin panel.

Configuration Caching Caveats in Laravel

Arie Visser • June 17, 2020

laravel php

What is configuration caching?

With configuration caching you can bundle all configuration files, to be loaded faster by Laravel.

When you run php artisan config:cache, a new file will be created in boostrap/cache/config.php. This file will contain an array with all the configuration values of your application. You can delete it by executing php artisan config:clear.

There are two common issues that might occur when using configuration caching, that can easily be avoided.

Do not use the env helper outside of configuration files

With the env helper method you can read values directly from your environment variables.

However, after caching the configuration files, the .env file will not be loaded anymore. As a result, the env method will always return null. This might give some serious issues in your application.

Only use the env helper in configuration files

Only use the env helper in configuration files, in order that the values from your .env file can be read, and added to boostrap/cache/config.php when running php artisan config:cache.

Avoid configuration caching in combination with PHPUnit

Another issue that might occur, is configuration caching in combination with PHPUnit tests.

PHPUnit allows you to assign values to environment variables that are used when running your tests, instead of the values from the .env file.

Those can be found in phpunit.xml, and might look like this:

    <env name="APP_ENV" value="testing"/>
    <env name="CACHE_DRIVER" value="array"/>
    <env name="SESSION_DRIVER" value="array"/>
    <env name="QUEUE_DRIVER" value="sync"/>
    <env name="SCOUT_DRIVER" value="null"/>

However, when you cache your config, PHPUnit will read the cached values, instead of the values that are defined in phpunit.xml for your testing environment. This will cause some unexpected behavior.

For example, the Illuminate\Foundation\Http\Middleware\VerifyCsrfToken middleware will not run when APP_ENV=testing. After caching your config, the APP_ENV will contain the value that is defined in your .env, even when you are running your tests. As a result, you might receive Expected status code 200 but received 419. Failed asserting that false is true when running your integration tests, since the VerifyCsrfToken middleware will be executed.

Do not cache your configuration files in an environment where you also run tests with PHPUnit.

The rule is to not cache your configuration files in a testing environment. If you have no other choice, you can run php artisan config:clear, or automate this in your TestCase.php by implementing the createApplication method and clear your cached config before each test:

use Illuminate\Support\Facades\Artisan; 

public function createApplication()