Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to load different .env file for multiple domain in single laravel app?

Tags:

php

laravel

I would like to access single laravel application by multiple domain.

For routing i have used laravel route pattern for eg.

$appRoutes = function() {
     Route::group(['namespace'=>"Interface1"], function(){

     /** route for index page and User authentication pages **/
     Route::get('/', 'LoginController@showLoginForm')->name('login'); 
 });
};

Route::group(array('domain' => 'example1.com'), $appRoutes);
Route::group(array('domain' => 'example2.com'), $appRoutes);

Now .env for each domain i have replaced config variable value inside AppServiceProvider.php register method:

   if(isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST']) ){ 
        if($_SERVER['HTTP_HOST']=='example1.com'){  
            $configArray = [
                'APP_NAME' => 'Application 1',
                'APP_URL'  =>  'http://example1.com', 
            ]; 
        }else{  
            $configArray = [
                'APP_NAME' => 'Application 2', 
                'APP_URL' =>  'http://example2.com, 
            ];  
        }  
        config($configArray);
    } 

but still i am not getting correct domain url using url(config('app.url'))

How to load all .env variable overwrite for each domain?

like image 604
Hetal Visaveliya Avatar asked Mar 07 '23 00:03

Hetal Visaveliya


1 Answers

For the current Laravel 7.x. at the time of writing this, you can add the following code in your bootstrap/app.php file just before return $app statement.

// bootstrap/app.php

// ...

/*
|-----------------------------------------------
| Load domain-specific .env file if it exists
|-----------------------------------------------
*/

if(isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST'])){
    $domain = $_SERVER['HTTP_HOST'];
}

if (isset($domain)) {
    $dotenv = Dotenv\Dotenv::createImmutable(base_path(), '.env.'.$domain);

    try {
        $dotenv->load();
    } catch (\Dotenv\Exception\InvalidPathException $e) {
        // No custom .env file found for this domain
    }
}

// ...

return $app;

Next, you should have a .env file for each domain in the following format .env.example1.com .env.example2.com. You can leave the original .env as a fallback for domains that lack an explicit .env file.

For Laravel 5.x or Laravel 6.x, you can find more from the original solution.

like image 116
Josh D. Avatar answered Mar 08 '23 23:03

Josh D.