LoginSignup
72
94

More than 5 years have passed since last update.

[Laravel5] 本番環境とテスト環境( or ローカル環境)で条件分岐させる方法 [PHP]

Last updated at Posted at 2016-06-21

Laravel 5.2.31, PHP 5.6.22, CentOS 6.8環境にて動作を確認

まずは.envで各環境を正しく区別させておきます。
.envの場所がわからない場合はroot権限で

find / -name .env 

で場所を検索してください。

  • 本番環境の場合 ※APP_DEBUGの値は変更しなくてもOKです
APP_ENV=production
APP_DEBUG=false
  • ステージング環境の場合
APP_ENV=staging
APP_DEBUG=false
  • テスト環境の場合
APP_ENV=testing
APP_DEBUG=true
  • ローカル環境の場合
APP_ENV=local
APP_DEBUG=true

設定が完了したら、条件分岐させたいPHPファイル内で次のように記述します。

if ( app()->isLocal() || app()->runningUnitTests() ) { // .env に APP_ENV=local (ローカル環境) または APP_ENV=testing (テスト環境) と書いてある場合
  // テスト環境, ローカル環境用の記述
}
else { // .env に APP_ENV=production (本番環境) などと書いてあった場合
  // 本番環境用の記述
}

以上。

追記

こんな書き方もできるみたいです。検証はしてませんが。
これ App::environment('testing') としてもうまく動かなかったのですが私の設定が何かおかしいのだろうか...

if (App::environment('production', 'staging')) {
 // 本番環境とステージング環境用
}

if (App::environment('local')) {
 // ローカル環境用
}

さらに追記

Laravelはじめたての頃に書いたものですが、いまだに結構アクセスがあるので、実際の使用例も載せておきます。

本番環境では、ページが見つからなければ自作の404ページ(resources/views/errors/404.blade.php)を表示、
サーバーエラーはOops Looks Like Something Went Wrongのアレじゃなくて自分で作った500ページ(resources/views/errors/500.blade.php)を表示

テスト環境とローカル環境では、自作の404ページと、サーバーエラーはOopsのアレを表示する

app/Exceptions/Handler.php
    public function render($request, Exception $e)
    {
        if ( app()->isLocal() || app()->runningUnitTests() ) {
            return parent::render($request, $e);
        }
        else {
            if ($this->isHttpException($e)) {
                return $this->renderHttpException($e);
            } else {
                return response()->view("errors.500");
            }
        }
    }
72
94
1

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
72
94