Since Laravel 5, it is interest to me - how to register and use console command from package in Laravel 5.
As 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 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 service provider in app.php & execute dump-autoload. But when i try to execute
php artisan eternaltree:install
it show me
[InvalidArgumentException] There are no commands defined in the "eternaltree" namespace.
I think my command is not registered by service provider, because php artisan list does not show my command. Can anyone explain to me what is the right way to register commands in own package in Laravel 5 ?
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
if ($this->app->runningInConsole()) {
$this->commands([
FooCommand::class,
BarCommand::class,
]);
}
}
Add a similar If
statement to your service provider class.
It is not required to use a service container and a singleton. You can simply put your command class into the $this->commands([]);
array into the register()
section of your service provider.
Like that :
$this->commands([
Acme\MyCommand::class
]);
I found a decision, it was simple:
in registerInstallCommand()
Add
$this->commands('command.eternaltree.install');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With