How to register a console command from a package in Laravel 5?

Starting with Laravel 5, I’m wondering how to register and use the console command from the package in Laravel 5.

Like in laracast, discuss https://laracasts.com/discuss/channels/tips/developing-your-packages-in-laravel-5 , I create a directory structure, add my package to autoload and create a service provider

<?php namespace Goodvin\EternalTree; use Console\InstallCommand; use Illuminate\Support\ServiceProvider; class EternalTreeServiceProvider extends ServiceProvider { public function boot() { } public function register() { $this->registerCommands(); } protected function registerCommands() { $this->registerInstallCommand(); } protected function registerInstallCommand() { $this->app->singleton('command.eternaltree.install', function($app) { return new InstallCommand(); }); } public function provides() { return [ 'command.eternaltree.install' ]; } } 

My InstallCommand.php script is stored in / src / Console

 <?php namespace Goodvin\EternalTree\Console; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; class InstallCommand extends Command { protected $name = 'install:eternaltree'; protected $description = 'Command for EternalTree migration & model install.'; public function __construct() { parent::__construct(); } public function fire() { $this->info('Command eternaltree:install fire'); } } 

I register the service provider in app.php and do dump-autoload. But when I try to execute

 php artisan eternaltree:install 

show me

 [InvalidArgumentException] There are no commands defined in the "eternaltree" namespace. 

I think that my team is not registered by the service provider, because my team is not displayed in the php artisan list. Can someone explain to me what is the correct way to register commands in my own package in Laravel 5?

+5
source share
3 answers

I found a solution, it was simple:

in registerInstallCommand() Add

 $this->commands('command.eternaltree.install'); 
+3
source

You do not need to use a service container and a singleton. You can simply put your command class into the $this->commands([]); array $this->commands([]); to the register() section of your service provider.

Like:

 $this->commands([ Acme\MyCommand::class ]); 
+18
source

Better late than never.

You tried to call eternaltree:install , but you registered the command as install:eternaltree .

Your answer is correct ... but there was no need for registerCommands() and registerInstallCommands() methods. Keep your code in order by simply calling the commands() method from the register() method.

-1
source

Source: https://habr.com/ru/post/1215996/


All Articles