Importing namespaces in Laravel Tinker REPL - laravel

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

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

Laravel, call Artisan from php differs from command line

I have a route which calls the Artisan facade to execute:
Artisan::call('queue:work --once');
And I get :
But it's strange because in the command line, if i do:
php artisan queue:work --once
Works everything ok:
I can use other routes to call for example:
Artisan::call('config:clear');
And works ok too. Any idea?
the options value staring with -- are not passed to the string
you can try :
Artisan::call('queue:work', ['--once' => true]);
Laravel 5.8 introduced this new method of calling artisan commands:
Artisan::call('queue:work --once');
In previous releases use this:
Artisan::call('queue:work', ['--once' => true]);
to call an artisan command from the code and passing some options you need to use an array as a 2nd argument to Artisan::call()
like so :
Artisan::call('queue:work', ['--once' => true]); // or whatever options you need

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

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

Doctrine 2 CLI commands from within PHP

Hey all. I am writing a program that will transform some data in our database, and then call Doctrine to build YAML files from said Mysql Database structure. I have Doctrine working from within PHP. However I can't figure out how to call the CLI commands from within PHP. Following is the Doctrine 2 CLI command that does what I need.
php ./doctrine orm:convert-mapping --filter="users" --from-database yml ./test
This command works from the Linux command line, but how to I do this same thing via Doctrine objects? I don't want to just use the PHP exec statement to send a command to the shell. I wish to use the Doctrine object model.
Don!:
Apparently this is not a very common programming method. However, I have used Doctrine from PHP by calling it via the PHP EXEC command. I know you said that you would not like to do it this way. However, it actually works quite well. Below is an example of such a solution.
$cmd_string = "php ./doctrine orm:generate-entities --generate-annotations=1 --regenerate-entities=1 $this->entity_file_dir";
$result = array();
exec($cmd_string, &$result);
Hope this helps,
-Don!
I stumbled upon this question when trying to execute a command directly from a PHP script, without using the CLI.
Particularly, I was needing to call orm:ensure-production-settings.
Each Doctrine command has its own class: http://www.doctrine-project.org/api/orm/2.4/namespace-Doctrine.ORM.Tools.Console.Command.html
I solved it the following way:
$entityManager = ...; // Get the entity manager somehow in your application
// Creates the helper set
$helperSet = \Doctrine\ORM\Tools\Console\ConsoleRunner::createHelperSet($entityManager);
// Initializes the desired command and sets the helper set
// In your case it should be ConvertMappingCommand instead
$command = new \Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand();
$command->setHelperSet($helperSet);
// Initializes the input
// Alternatives: http://api.symfony.com/2.0/Symfony/Component/Console/Input.html
$input = new \Symfony\Component\Console\Input\ArgvInput(); // Input coming from the CLI arguments
// Initializes the output
// Alternatives: http://api.symfony.com/2.0/Symfony/Component/Console/Output.html
$output = new \Symfony\Component\Console\Output\ConsoleOutput(); // Prints the output in the console
// Runs the command
$command->run($input, $output);
I'm new to Doctrine so I'm not exactly sure how this works, but it does. Any comment is appreciated.

Resources