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

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()

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');

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

Related

Laravel env() value null

I'am trying to retrieve EXAMPLE_URL=www.google.com from .env in controller and everytime get null. Where is the problem because the same code works on another application. This function doesn't work after php artisan cache:clear.
Controller code
$hostname = env("EXAMPLE_URL");
dump($hostname);
You should not use env() outside of the config files.
Read: https://laravel.com/docs/8.x/configuration
You should add the env variable to a config file and use config('example.url');.
The example.php would look like:
return [
'url' => env('EXAMPLE_URL', 'https://example.com'),
];
Always use the app file as the middleman
see : https://laravel.com/docs/9.x/configuration

The use statement with non-compound name 'Session' has no effect

$ php artisan serve
ErrorException
The use statement with non-compound name 'Session' has no effect
at routes/web.php:6
3▕ use Illuminate\Support\Facades\Route;
4▕ use Illuminate\Http\Request;
5▕ use Illuminate\Foundation\Application;
➜ 6▕ use Session;
7▕
The error says that doing use Session in the root namespace does not actually do anything because Session is already in the root namespace.
In reality Session does not exist in the root namespace but is rather an alias defined in config/app.php. Bottom line is when you are in the root namespace already you don't need to do use Session.
While you don't need to do this, what I suggest you do is:
use Illuminate\Support\Facades\Session
Alternatively you can use the session helper function:
session()
and you can also retrieve the session singleton using the application container:
app()->make('session');
This is just because personally I don't like global aliases. Your opinion may differ.

Php artisan - custom command

I would like to create my own php artisan command so when I write
php artisan env:[variable]
I want to get that variable, so I can check fast if I'm getting the right variable from .env file
Is this possible? How to do it?
You can create a console command with:
php artisan make:console
As per the docs.
You are probably better off creating a static signature and passing in the field you want to return.
protected $signature = 'env:return {field}';
This will allow you to type php artisan env:return APP_DEBUG.
You can retrieve the input like so:
public function handle()
{
$envVariable = $this->argument('field');
//
}
You can then write some code to output the field, perhaps something like:
$this->info(env($envVariable));
This could all be condensed down into something like the below, as an example only:
protected $signature = 'env:return {field}';
public function handle()
{
$this->info(env($this->argument('field')));
}
I would suggest you read the docs I linked above as this will help you understand what is happening here a lot more.
This should get you started though, and you can then shape it to be exactly what you need.

Importing namespaces in Laravel Tinker REPL

Laravel's Tinker REPL is useful for conveniently experimenting with models, however it does not seem possible to import a namespace, requiring the model namespace to be laboriously typed. For instance, this works:
$ php artisan tinker
[1] $list = new mysweetapp\Todolist;
[2] > echo get_class($list);
mysweetapp\Todolist
This does not:
$ php artisan tinker
[1] use mysweetapp\Todolist;
// false
[2] $list = new Todolist;
[3] echo get_class($list);
Boris\EvalWorker
Is there some way to import namespaces into Tinker or is it just not yet supported? Mind you I definitely want to use namespaces, I just don't want to repeatedly type in the namespace. :-)
Look at this https://softonsofa.com/tinker-like-a-boss-in-psysh/
You can't do this with use namespace in the repl itself, but here's what you may do:
// config/local/app.php
'aliases' => append_config([
'Todolist' => 'Mysweetapp\Todolist',
... // more
]),
Then in your local env you will be able to access your models without typing namespace, and if you're not in local env, then run tinker forcing it:
php artisan tinker --env=local

Custom artisan commands with multiple 'methods' (in the style of migrate:install etc)

I'm creating a custom artisan command (foo) for my Laravel 4 application. I can see from the userguide how to accept arguments and options, e.g.
php artisan foo argument --option
But what if I want to have a custom artisan command that has many 'methods', in the same style as some built-in artisan commands, e.g. migrate:install?. I want to make something like:
php artisan foo:baz argument --option
What is the recommended way to implement different methods based on the : colon separator? All I've found to try so far is to make an entirely new artisan command for each 'method'. Is there a more efficient way?
You're correct, you do need a new Artisan command (or rather a class) for each method. However all you have to do is register each file in app/Console/Kernel.php, if you decide to change the syntax later than Laravel will pick it up any changes to $signature automatically without you needing to rename any files.
For the Laravel example you mention, migrate, there's a directory with a separate file for each command name (including the one that has no colon):
/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations
migrate -> MigrateCommand.php
migrate:install -> InstallCommand.php
migrate:refresh -> RefreshCommand.php
migrate:reset -> ResetCommand.php
migrate:rollback -> RollbackCommand.php
migrate:status -> StatusCommand.php
If you have code you want to reuse (DRY) note that if you examine the above commands, some of them use traits, e.g. Illuminate\Console\ConfirmableTrait – which contains a confirmToProceed() method which, if it's running in production, will ask the user if they really want to continue.
NB: the Artisan syntax changed in 5.1, from $name (with a rather complicated way of specifying arguments and options) to the much simpler $signature, it's backwards compatible. More info
You just have to set the name:
protected $name = 'foo:baz';

Resources