How Laravel Loads Environment Variables During Bootstrap
This article explains Laravel's bootstrapping process for loading environment variables, detailing each step from configuration cache checking to creating a Dotenv instance, parsing the .env file, and handling related exceptions, with code examples illustrating the workflow.
Laravel loads its environment variables during the bootstrapping phase, which is handled by the Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables class. The process is straightforward and consists of several clearly defined steps.
<code>class LoadEnvironmentVariables
{
/**
* Bootstrap the given application
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return void
*/
public function bootstrap(Application $app)
{
if ($app->configurationIsCached()) {
return;
}
$this->checkForSpecificEnvironmentFile($app);
try {
$this->createDotenv($app)->safeLoad();
} catch (InvalidFileException $e) {
$this->writeErrorAndDie($e);
}
}
}
</code>Step Analysis
1. Check configuration cache
The bootstrap method first checks whether the application configuration has been cached. If it is cached, the method returns early and skips loading environment variables.
<code>if ($app->configurationIsCached()) {
return;
}
</code>2. Check environment configuration file
Next, the method checks for a specific environment file. For example, if the current environment is production , it looks for a .env.production file.
<code>$this->checkForSpecificEnvironmentFile($app);
</code>3. Create and load .env file
If no specific environment file exists, Laravel creates a default .env file and loads the variables from it.
<code>try {
$this->createDotenv($app)->safeLoad();
} catch (InvalidFileException $e) {
$this->writeErrorAndDie($e);
}
</code>Configuration Cache
1. Check if configuration cache file exists
The configurationIsCached method checks for the presence of ./config.php in the cache directory. If the file exists, configuration is considered cached.
<code>public function configurationIsCached()
{
return is_file($this->getCachedConfigPath());
}
</code>2. Get configuration cache file path
The getCachedConfigPath method returns the full path to the cached configuration file.
<code>public function getCachedConfigPath()
{
return $this->normalizeCachePath('APP_CONFIG_CACHE', 'cache/config.php');
}
</code>Configuration Not Cached
1. Check if a specific environment file is specified
If the application runs in the console with a --env option, Laravel sets the environment file to the one specified by that option.
<code>protected function checkForSpecificEnvironmentFile(Application $app)
{
if ($app->runningInConsole() &&
($input = new ArgvInput)->hasParameterOption('--env') &&
$this->setEnvironmentFilePath($app, $app->environmentFile() . '.' . $input->getParameterOption('--env')))
{
return;
}
// ...
}
</code>2. Retrieve environment variables
Laravel reads the APP_ENV variable from the .env file.
<code>$environment = Env::get('APP_ENV');
</code>3. Set environment file
If the APP_ENV variable exists, Laravel sets the environment file to .env.{APP_ENV} .
<code>if ($environment) {
$this->setEnvironmentFilePath($app, $app->environmentFile() . '.' . $environment);
}
</code>Read .env File Parsing
1. Determine environment file
Before loading variables, Laravel determines which environment file to use, checking external environment variables and CLI parameters.
External environment variable: whether APP_ENV is provided by the system.
CLI parameter: whether a --env option was supplied.
1.1 Get APP_ENV from external environment variables
If APP_ENV exists in the system environment, Laravel uses its value as a suffix (e.g., .env.production ).
1.2 Get environment file from CLI parameter
When a --env option is passed (e.g., php artisan serve --env=staging ), Laravel attempts to load .env.staging .
1.3 Load default environment file
If neither condition applies, Laravel falls back to the default .env file.
2. Create Dotenv instance
After determining the file, Laravel creates a Dotenv instance to handle loading and parsing.
3. Parse .env file
The Dotenv instance uses safeLoad to load the file safely, handling missing files or format errors.
3.1 Safely load .env file
safeLoad attempts to read the file; if it cannot, an empty array is returned.
3.2 Parse .env file contents
safeLoad calls load , which reads the file and passes its contents to parse for conversion into a key‑value array.
3.3 Parse .env file format
The parse method interprets each line of the .env file and builds the configuration array.
4. Exception handling
InvalidPathException : thrown when the .env file is missing or unreadable.
InvalidFileException : thrown when the .env file has an invalid format.
<code>// Determine environment file
$envFile = $app->environmentFile();
if ($app->runningInConsole() && $input = new ArgvInput()) {
if ($input->hasParameterOption('--env')) {
$envFile = $app->environmentPath() . '.' . $input->getParameterOption('--env');
}
}
// Create Dotenv instance
$dotenv = Dotenv::create(
Env::getRepository(),
$app->environmentPath(),
$envFile
);
// Parse .env file
try {
$dotenv->safeLoad();
} catch (InvalidFileException $e) {
$this->writeErrorAndDie($e);
}
</code>Summary
1. Cache check
Laravel first checks whether environment variables have been cached; if so, it reads them directly.
2. Environment file determination
The framework selects the appropriate .env file based on the --env CLI option or the APP_ENV variable.
3. Dotenv instance creation
A Dotenv instance is created to load and parse the selected .env file.
4. Safe loading of environment variables
The safeLoad method loads the .env file while handling potential errors.
5. Exception handling
Laravel gracefully handles missing files or format errors by catching and reporting the relevant exceptions.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.