Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 Dotenv for specific subdomain

I have a few subdomain in my laravel 5 application, each sub domain have a specific configuration, like mail, nocaptcha, etc.

how to set .env file to work with my-specific subdomain ?

like image 934
comenk Avatar asked Mar 17 '23 07:03

comenk


1 Answers

Yes, you can use separate .env files for each subdomain so if you use env variables in your config it will work without great modifications.

Create bootstrap/env.php file with the following content:

<?php
$app->detectEnvironment(function () use ($app) {
    if (!isset($_SERVER['HTTP_HOST'])) {
        Dotenv::load($app['path.base'], $app->environmentFile());
    }

    $pos = mb_strpos($_SERVER['HTTP_HOST'], '.');
    $prefix = '';
    if ($pos) {
        $prefix = mb_substr($_SERVER['HTTP_HOST'], 0, $pos);
    }
    $file = '.' . $prefix . '.env';

    if (!file_exists($app['path.base'] . '/' . $file)) {
        $file = '.env';
    }

    Dotenv::load($app['path.base'], $file);
});

Now modify bootstrap/app.php to load your custom env.php file. Just add:

require('env.php');

after

$app = new Illuminate\Foundation\Application(
    realpath(__DIR__.'/../')
);

Now you can create separate env files for each domains for example if you use testing.app, abc.testing.app and def.testing.app you can have .env file for main domain (and for all subdomains that don't have custom env files) and .abc.env and .def.env files for custom env variables your your subdomains.

like image 141
Marcin Nabiałek Avatar answered Mar 24 '23 22:03

Marcin Nabiałek