I’m working on a Laravel 11 project and I need to set up environment-aware configurations that is accessible with config
method. For example, I have a constant.php
file in the config
directory for general configurations, and a constant.php
file in the config/production
directory for production-specific configurations.
Here’s the directory structure:
config/
constant.php
config/production/
constant.php
I want to achieve the following:
config('constant')
On local and staging environments, load only the config/constant.php
.
On production environment, load both config/constant.php
and config/production/constant.php
, with config/production/constant.php
overriding any overlapping configurations from config/constant.php.
How can I configure Laravel 11 to achieve this environment-aware configuration loading?
Code samples or any specific methods would be greatly appreciated!
Additional context:
I’m familiar with Laravel’s env() function and configuration caching, but I’m not sure how to implement this selective configuration loading based on the environment.
2
Answers
Ohk,I solved it :) To create environment-aware configurations in Laravel 11, you can extend the configuration repository in your
AppServiceProvider
. This method dynamically merges environment-specific configurations with the general configurations based on the current environment.This code might be simpler to what you currently are using:
Add this in any service provider
register
function:All your constants should be available using
config('constant.constantname')
The
if !File::exists(Application::getInstance()->getCachedConfigPath()))
is there because if the config is cached then this provider would have ran before caching and the config change would already be there (so there’s no need to run it again)