LoginSignup
135
100

More than 5 years have passed since last update.

Laravel では env() を config 系ファイル以外の場所に書いてはいけない

Last updated at Posted at 2018-01-24

説明するよりもフレームワークのコード読んでもらったほうが早いので掲載します。

framework/LoadEnvironmentVariables.php L12-L31

    /**
     * Bootstrap the given application.
     *
     * @param  \Illuminate\Contracts\Foundation\Application  $app
     * @return void
     */
    public function bootstrap(Application $app)
    {
        if ($app->configurationIsCached()) {
            return;
        }

        $this->checkForSpecificEnvironmentFile($app);

        try {
            (new Dotenv($app->environmentPath(), $app->environmentFile()))->load();
        } catch (InvalidPathException $e) {
            //
        }
    }

.env ファイルの読み込みは, php artisan config:cache していない場合にしか行われません! キャッシュを有効にしてある場合, .env に書いてあるだけでシェルから起動する時点で定義されていない環境変数はすべて未定義になってしまうので注意しましょう。

要するに

config/app.php
    'env' => env('APP_ENV', 'production'),

こういう使い方はOKで,

app/User.php
class User extends Model
{
    public function debug(): string
    {
        if (env('APP_ENV', 'production') === 'production') {
            /* ... */
        } else {
            /* ... */
        }
    }
}

こういう使い方はダメだと言うことです。環境変数で分岐させたい場合は,一度必ずconfig/*.phpの中に落としましょう。

135
100
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
135
100