How can I call command schedule via url on the laravel?

有些话、适合烂在心里 提交于 2020-01-17 15:25:10

问题


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



来源:https://stackoverflow.com/questions/52135339/how-can-i-call-command-schedule-via-url-on-the-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!