How can I call command schedule via url on the lar

2019-09-20 05:27发布

问题:

I using laravel 5.6

I set my schedule in the kernel.php like this :

<?php
namespace App\Console;
use App\Console\Commands\ImportLocation;
use App\Console\Commands\ImportItem;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
    protected $commands = [
        ImportLocation::class,
        ImportItem::class,
    ];
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('inspire')->dailyAt('23:00');

    }
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');
        require base_path('routes/console.php');
    }
}

So there are two command

I will show one of my commands like this :

namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\Location;
class ImportLocation extends Command
{
    protected $signature = 'import:location';
    protected $description = 'import data';
    public function __construct()
    {
        parent::__construct();
    }
    public function handle()
    {
        ...
    }
}

I want to run the command via url. So it not run in the command promp

I try like this :

I add this script : Route::get('artisan/{command}/{param}', 'CommandController@show'); in the routes and I make a controller like this :

namespace App\Http\Controllers;
class CommandController extends Controller
{
    public function show($command, $param)
    {
        $artisan = \Artisan::call($command.":".$param);
        $output = \Artisan::output();
        return $output;
    }
}

And I call from url like this : http://myapp-local.test/artisan/import/location

It works. But it just run one command

I want to run all command in the kernel. So run import location and import item

How can I do it?

回答1:

What you can do is register a custom method in your Kernel.php to retrieve all custom registered commands in the protected $commands array:

public function getCustomCommands()
{
    return $this->commands;
}

Then in your controller you can loop them all and execute them via Artisan's call() or queue() methods:

$customCommands = resolve(Illuminate\Contracts\Console\Kernel::class)->getCustomCommands();

foreach($customCommands as $commandClass)
{
    $exitCode = \Artisan::call($commandClass);
    //do your stuff further
}

More on Commands you can understand on the documentation's page