Search code examples
phplaravellaravel-artisanapiato

How to call a handle method into an routes.php file?


I want to print a log message when i run php artisan make:greetings command in my command line it should return a message in my log file , for that how to call a handle method inside the routes.php file, for that i am writing some code but i am getting a following error please help me to fix this issue

Error

   TypeError 

  Argument 2 passed to Illuminate\Foundation\Console\Kernel::command() must be an instance of Closure, array given, 
called in C:\apiato-project\apiato\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php on line 261   

  at C:\apiato-project\apiato\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php:191
    187▕      * @param  string  $signature
    188▕      * @param  \Closure  $callback
    189▕      * @return \Illuminate\Foundation\Console\ClosureCommand
    190▕      */
  ➜ 191▕     public function command($signature, Closure $callback)
    192▕     {
    193▕         $command = new ClosureCommand($signature, $callback);
    194▕
    195▕         Artisan::starting(function ($artisan) use ($command) {

  1   C:\apiato-project\apiato\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php:261
      Illuminate\Foundation\Console\Kernel::command("make:greetings", ["App\Console\Commands\Hello"])

  2   C:\apiato-project\apiato\app\Ship\Commands\Routes.php:24
      Illuminate\Support\Facades\Facade::__callStatic("command")

routes.php

 Artisan::command('make:greetings',[Hello::class,'handle'=>true]);

Hello.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Log;

class Hello extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'make:greetings';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        
        return Log::info("welcome message");
    }
}


Solution

  • The second argument have to be a closure and you are passing an array, This closure is used to pass data to your handle method and as you dont have any arguments in your handle method use call method istead of command, Try this:

    Artisan::call('make:greetings');
    

    and also don't forget to register your command in App\Console\Kernel class:

        protected $commands = [
            'App\Console\Commands\Hello',
        ];