How to send parameters to queues?

2020-08-26 11:15发布

问题:

Please consider the following job:

<?php

namespace App\Jobs;

use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ImportUsers extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    public function __construct($number)
    {
        $this->number=$number;
    }

    public function handle()
    {
        dd($this->number);
        return;
    }
}

Dispatching this job using a sync queue $this->dispatch(new \App\Jobs\ImportUsers(5)); throw this exception: Undefined property: App\Jobs\ImportUsers::$number. This really seems odd for me. Why the handle method can not access class properties?

回答1:

Properly declare your property

class ImportUsers extends Job implements SelfHandling, ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    protected $number; // <-- Here

    public function __construct($number)
    {
        $this->number=$number;
    }

    public function handle()
    {
        dd($this->number);
        return;
    }
}

What happens is after the jobs is being deserialized from the queue you loose dynamically created property.

Try it:

$ php artisan tinker
>>> Bus::dispatch(new App\Jobs\ImportUsers(7));
7
>>>