Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel command called from Laravel job

I have a command named MyCommand, and I am calling it from a job named MyJob. I cannot see the command outputs when it's called from job. But if I run the command directly from command line, command output is seen.

MyCommand.php code:

namespace App\Console\Commands;

use Illuminate\Console\Command;

class MyCommand extends Command
{

    protected $signature = 'mycommand:doit';

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

    public function handle()
    {
        $this->info('Process started');

        //Some process is done here

        $this->info('Process completed');
    }
} 

MyJob.php code:

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Artisan;

class MyJob implements ShouldQueue
{
    public function __construct()
    {

    }

    public function handle()
    {
        Artisan::call('mycommand:doit');
    }
} 
like image 905
Umut KIRGÖZ Avatar asked May 29 '19 10:05

Umut KIRGÖZ


1 Answers

As in theory, you are not in a terminal with you run your job (Job may for example, be queued or scheduled), output is not saved when run outside a terminal.

However, you can still get the output buffer with Artisan::output();

Example:

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Artisan;

class MyJob implements ShouldQueue
{
    public function __construct()
    {

    }

    public function handle()
    {
        Artisan::call('mycommand:doit');
        $output = Artisan::output(); // $output is a string

        // Do whatever you want with $output
    }
}

Update: synchronous output

You may try this: Example of command:

class SlowCommand extends Command
{
    protected $signature = "slow";


    public function handle()
    {
        $max = 10;

        for ($i = 0; $i < $max; $i++) {
            $this->line($i);
            sleep(1);
        }
    }
}
// Synchronous output
Artisan::call("slow"); 
echo Artisan::output();

// Asynchronous output
$buffer = new ConsoleOutput();
Artisan::call("slow", [], $buffer);
like image 122
Mathieu Bour Avatar answered Nov 10 '22 10:11

Mathieu Bour