phplaravelenvironmentschedule

Get laravel environment when running schedule


I set up some commands in Laravel 5 schedule. The output is stored in the file and emailed to me.

Since there are several "copies" of the project I wanna use the environment name to be able to tell which copy the email came from.

I tried using app()->environment() in schedule description - it throws an error:

Fatal error: Uncaught exception 'ReflectionException' with message 'Class env does not exist' in ...

I also tried getenv('APP_ENV') - this does not cause any error, but I get a blank environment name.

App::environment() didn't work either.

All of these work just fine if I use them in regular requests (for example controller actions or views).

Is there a way to determine current environment when running schedules?

Thank you


Solution

  • I found a solution.

    In my App\Console\Kernel schedule method, right before setting app all the schedules I added a line:

    Dotenv::required('APP_ENV');
    

    Keep in mind that you either have to use Dotenv; or add a \ to the line above because of the namespaces.

    This way the system "makes sure" the APP_ENV is loaded and app()->environment() is returning correct environment name.