Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 380
MaGnetas Avatar asked Nov 30 '25 16:11

MaGnetas


2 Answers

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.

like image 64
MaGnetas Avatar answered Dec 03 '25 09:12

MaGnetas


The other answer doesn't work for Laravel 5.3 because Dotenvshould not be called statically. Additionally it needs the path to the .env file as the first parameter.

You can use this instead (assumped you are inside /app/Providers/AppServiceProvider.php):

$env = new Dotenv(realpath(__DIR__.'/../../'.'.env'));
$env->required('APP_ENV');
like image 43
Lars Avatar answered Dec 03 '25 07:12

Lars



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!