Laravel - custom .env file

前端 未结 6 1888
难免孤独
难免孤独 2020-12-31 19:41

Laravel assumes that .env file should describe environment, and it should not be committed to your repo.

What if I want to keep both .env f

6条回答
  •  灰色年华
    2020-12-31 20:07

    I like to add a solution for people who have a shared codebase for many vhosts that all need different .env files for all the different things, like database connections, smtp settings etc.

    For every vhost, on Apache, create a vhost config:

    
        ServerName your-vhost.yourdomain.com
        DocumentRoot /var/www/shared-codebase/public
    
        SetEnv VHOST_NAME 'your-vhost'
    
        
        Options Indexes MultiViews FollowSymLinks
        AllowOverride all
        Order deny,allow
        Require all granted
        
    
        
           AssignUserId your-vhost your-vhost
        
    
        ErrorLog /var/www/your-vhost/logs/error.log
        CustomLog /var/www/your-vhost/logs/access.log combined
    
    

    All vhosts have the same document root and directory, because it is a shared codebase. Inside the config we added a SetEnv VHOST_NAME 'your-vhost' which we will later use in Laravel's bootstrap.php to change the location of vhost specific .env.

    Next create the custom .env file in a folder(fe. /var/www/your-vhost/.env) the alter bootstrap.php so that it loads the .env from the right location.

    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
    );
    
    /*
    |--------------------------------------------------------------------------
    | Add the location of the custom env file
    |--------------------------------------------------------------------------
    */    
    $app->useEnvironmentPath('/var/www/'.$_SERVER['VHOST_NAME']);
    
    return $app;
    

    That's all.

    [edit] I you want to target a specific database or want to generate a key for a specific .env, then you should put the VHOST_NAME in front of the artisan command.

    VHOST_NAME=tenant2.domain.com php artisan key:generate
    

    [edit] When working locally and are using Laravel Valet, then you can add a custom .valet-env.php in the root of your codebase. https://laravel.com/docs/master/valet#site-specific-environment-variables

提交回复
热议问题