Question:
How to make Laravel find out about the .env file that I want to load?
The subdomain name matches the .env file, I load it with Dotenv and also with the Laravel application with the loadEnvironmentFrom method.
Then I run:
php artisan config:cache
And finally when checking $ _ENV or getenv (string) I can see that it is well loaded, but … It is not like that, Laravel continues pointing to the .env file
bootstrap / app.php :
$app = new Illuminate\Foundation\Application(
realpath(__DIR__.'/../')
);
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
if (isset($_SERVER['HTTP_HOST'])) {
$hostArray = explode('.', $_SERVER['HTTP_HOST']);
$envFile = sprintf('.%s.env', $hostArray[0]);
$path = __DIR__.'/../';
if (count($hostArray) > 2 && file_exists($path, $envFile)) {
$dotenv = new Dotenv\Dotenv($path, $envFile);
$dotenv->load();
$app->loadEnvironmentFrom($envFile);
}
}
return $app;
Answer:
When I have done similar things, I have had success using the overload()
method of the DotEnv Loader, so that the instance is mutable, although I am not 100% sure that it is the problem in this case, I propose it as the first answer:
$dotenv = new Dotenv\Dotenv($path, $envFile);
$dotenv->overload();
EDITION:
After testing the OP's code in a pre-production environment and reviewing the PHP documentation, the error is that you are passing two parameters instead of one in the file_exists () function, which only accepts one parameter ( see documentation ).
Once this error is corrected, the correct .env is read using both the load()
and overload()
of Dotenv.
The correction is then, to form a single string with $path
and with $envFile
:
if (isset($_SERVER['HTTP_HOST'])) {
$hostArray = explode('.', $_SERVER['HTTP_HOST']);
$envFile = sprintf('.%s.env', $hostArray[0]);
$path = __DIR__.'/../';
if (count($hostArray) > 2 && file_exists($path . $envFile)) {
$dotenv = new Dotenv\Dotenv($path, $envFile);
$dotenv->load();
$app->loadEnvironmentFrom($envFile);
}
}