blog cover

Creating Separate Env File for Laravel in Localhost

January 14, 2023

In some cases, you may want the settings used on the server to be different from the settings used on your local server. For example: if you are using a local database.

In this case it might work to create a separate .env file for a separate server for localhost. What you need to do for this is to create a file named .env.local (or any name you want. I chose this name because it is more understandable.), or you can copy the ".env" and change its content. Then add the following code to the bootstrap/app.php file.

| Create The Application
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
$app = new Illuminate\Foundation\Application(
    $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
// load different enviroment file for localhost
if(file_exists(getcwd()."/.env.local")) $app->loadEnvironmentFrom('.env.local');

The point you should pay attention to here is that you should only have the env.local file on the local server. You should not upload this file to the actual server because as you can see from the code, the system loads the env settings from here as soon as it detects this file.