Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send parameters to queues?

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?

like image 555
Handsome Nerd Avatar asked Sep 30 '15 03:09

Handsome Nerd


1 Answers

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
>>> 
like image 199
peterm Avatar answered Nov 12 '22 16:11

peterm