Search code examples
phplaravellaravel-queue

Fail after adding parameters to job in Laravel


A job I've written before without parameters now needs them. It's meant to send an email using the Mail class. I need to execute this job now with parameters but the queue is not seeing them.

I wonder if I'm initializing SendMailFinished in a wrong way but it should be ok.

I've read that there are issues with serialization but I added protected variables in SendMailFinished.

class ReporteBCH implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     * No hay que pasar ninguna variable.
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Busca todos los equipos del inventario, luego revisa el SCCM con sus relaciones y el bginfo
     *
     * @return void
     */
    public function handle()
    {
        $msg = 'Proceso terminado. Ver ' . url('');
        $subj = 'Proceso BCH';
        $mailto = env('MAIL_TO');
        $send = new SendMailFinished($msg, $subj, $mailto);
        $send->dispatch();
    }


}

Now the thing is the process fails when I fire it from the console because it doesn't see parameters as if I didn't add them within the constructor.

SendMailFinished looks like this:

class SendMailFinished implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public $tries = 3;

    protected $msg;

    protected $subj;

    protected $mailto;


    public function __construct($msg, $subj, $mailto)
    {
        //
        $this->msg = $msg;
        $this->subj = $subj;
        $this->mailto = $mailto;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //Envia correo cuando termine cola.
        Mail::to($this->mailto)->queue(new TasksFinished($this->msg, $this->subj));
    }
}

The error is the following one:

Symfony\Component\Debug\Exception\FatalThrowableError: Too few arguments to function App\Jobs\SendMailFinished::__construct(), 0 passed in C:\laragon\www\reportes\vendor\laravel\framework\src\Illuminate\Foundation\Bus\Dispatchable.php on line 26 and exactly 3 expected in C:\laragon\www\reportes\app\Jobs\SendMailFinished.php:31

I've read https://laravel.com/docs/5.8/queues#creating-jobs but there's not much to learn about it and also this one How to send parameters to queues?


Solution

  • Well, the answer in the end is that arguments can't be passed as in a normal class and instead they have to be addded to the dispatch class all in one go.

    This doesn't work:

    $send = new SendMailFinished($msg, $subj, $mailto);
            $send->dispatch();
    

    This works:

    SendMailFinished::dispatch($msg, $subj, $mailto);
    

    Found an explanation within Laravel issues