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 loaded correctly, but... It is not, Laravel keeps 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;
When I have done similar things, I have had success using the
overload()
DotEnv Loader method, to make the instance mutable, although I am not 100% sure that it is the problem in this case, I propose it as a first answer: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 Dotenv
load()
and functionoverload()
.The correction is then, to form a single string with
$path
and with$envFile
:Checking the class
Dotenv\Dotenv
in the methodload
Generates an instance of the object
Dotenv\Loader
, whose second parameter is a boolean value that indicates if the loader object will be immutable (it will not overwrite the variables already set), when making the callload()
we tell it not to overwrite the parameter of the same function, and when generating the objectLoader
we tell it to be immutable, for that reason it doesn't load the file you need. You must call the methodoverload
of the same classDotEnv
defined as follows:leaving your code like this