DEV Community 👩‍💻👨‍💻

Cover image for Lazy load config on Laravel
prog-24
prog-24

Posted on

Lazy load config on Laravel

It is common knowledge that configuration on Laravel applications are one of the very first things to load. If it is not, well, check out the application lifecycle here. As part of the autoconfiguration of Laravel, everything in the config folder is considered an application configuration and loads pretty much as soon as the application is booted.

Why is this important? We will get to that in a second. First how can we achieve this.

The first step is to create a custom service provider. If you are not sure what these are, here is the doc for it.

I created one called CustomConfigServiceProvider. You can place this in the Providers directory.

Next create a new custom folder for your custom configuration files. Remember, everything in config is autoloaded. I created a folder called custom-config

In the boot section of the provider, add the following piece of code.

parent::boot();
$this->mergeConfigFrom(__DIR__.'/../../../custom-config/settings.php', 'settings');
Enter fullscreen mode Exit fullscreen mode

You are probably thinking, what is happening here? Let me break it down. Here is how your file should look:

<?php

namespace App\Providers\Custom;

use Illuminate\Support\ServiceProvider;

class CustomConfigServiceProvider extends ServiceProvider
{
    public function boot()
    {
        parent::boot();
        $this->mergeConfigFrom(__DIR__.'/../../../custom-config/settings.php', 'settings');
    }

    public function register()
    {
        parent::register();
    }
}
Enter fullscreen mode Exit fullscreen mode

First since every provider is extending the base ServiceProvider class from the framework, we are calling parent::boot() to ensure the code block runs first.
Then we are merging our new configuration into the configuration set that was already loaded previously. In this case, we have a custom configuration file called settings.php

Now you have everything set up for your lazy loaded configuration.

There is just one last step to complete. We need to register our service provider. In your config/app.php file, add your new provider in the providers array.

Viola, you now have lazy loaded configuration.

For the use cases, there are numerous, for instance, if you have a configuration that relies on a third-party application to have been loaded previously. More on this later.

Check out some cool features of Laravel 9. Are you using lazy loaded configurations? Let me know in the comments.

Top comments (2)

What image format should you use in your next project? 🤔