Don40
Don40

Reputation: 417

How to use ENV variables in Artisan Commands in Laravel 5.8?

I am creating my own artisan command and I want to use ENV variables, but when I use $_ENV['VariableName'] I get and error.

local.ERROR: Undefined index: VariableName

The same code works perfectly in a controller and error as this one is not being generated.

I am creating my commands with php artisan make:command CommandName

How can I start using ENV variables there? Thank you! I want to use the variables in a private function which is inside:

class CommandName extends Command but outside the public function handle()

Upvotes: 3

Views: 5918

Answers (2)

Moritz Schmid
Moritz Schmid

Reputation: 153

You can use the Laravel Helper to access environment variables with something like this:

env('VariableName')

you can also specify a default value if the environment variable is not set

env('VariableName', 'myName')

Laravel Docs 5.8 Helpers

Upvotes: 6

nakov
nakov

Reputation: 14248

Since the .env file is not pushed to the repository, the best approach is to use config files instead. So in the config directory, create your custom file for example: custom.php with the following content:

<?php

return [
   'variable' => env('VARIABLE_NAME', 'DEFAULT_VALUE')
];

and in your .env you should put:

VARIABLE_NAME=something

Then to use it you use config('custom.variable');

Upvotes: 7

Related Questions