Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 - Creating Artisan Command for Packages

I have been following along http://laravel.com/docs/5.0/commands and able to create artisan command in Laravel 5. But, how can I create artisan command and package it to packages?

like image 518
user1995781 Avatar asked Feb 13 '15 04:02

user1995781


People also ask

Which artisan command makes another artisan command?

To call another Artisan command and save its output you should use $this->call() from your command.

How do I register my artisan command?

Laravel Artisan Creating and registering new artisan command after creating command you can register your command inside app/Console/Kernel. php class where you will find commands property. so you can add your command inside the $command array like : protected $commands = [ Commands\[commandName]::class ];

How do I change artisan command in Laravel?

If you want to change behavior in an artisan command you can just create your own command class, extend Laravels class and register your command in Kernel. php as normal. As of Laravel 5.5 your class will be called in stead of the one provided by Laravel!


2 Answers

You can and should register the package commands inside a service provider using $this->commands() in the register() method:

namespace Vendor\Package;

class MyServiceProvider extends ServiceProvider {

    protected $commands = [
        'Vendor\Package\Commands\MyCommand',
        'Vendor\Package\Commands\FooCommand',
        'Vendor\Package\Commands\BarCommand',
    ];

    public function register(){
        $this->commands($this->commands);
    }
}
like image 75
lukasgeiter Avatar answered Oct 12 '22 00:10

lukasgeiter


In laravel 5.6 it's very easy.

class FooCommand,

<?php

namespace Vendor\Package\Commands;

use Illuminate\Console\Command;

class FooCommand extends Command {

    protected $signature = 'foo:method';

    protected $description = 'Command description';

    public function __construct() {
        parent::__construct();
    }

    public function handle() {
        echo 'foo';
    }

}

this is the serviceprovider of package. (Just need to add $this->commands() part to boot function).

<?php
namespace Vendor\Package;

use Illuminate\Events\Dispatcher;
use Illuminate\Support\ServiceProvider;

class MyServiceProvider extends ServiceProvider {

    public function boot(\Illuminate\Routing\Router $router) {
        $this->commands([
            \Vendor\Package\Commands\FooCommand ::class,
        ]);
    }
}

Now we can call the command like this

php artisan foo:method

This will echo 'foo' from command handle method. The important part is giving correct namespace of command file inside boot function of package service provider.

like image 32
vimuth Avatar answered Oct 11 '22 22:10

vimuth