3

I want to pass a closure function to job dispatch method of Laravel queue. But i am getting "Serialization of 'Closure' is not allowed" exception. Can anyone please tell me how i can be able to pass closure function to the dispatch method?

Here are the controller codes:

public function syncProductByQueue($id){
    $syncCallback=function() use($id){
        $this->syncProduct($id);
    };
    ProcessSyncImport::dispatch($syncCallback);
}

And here is the job class:

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;

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

    /**
     * Create a new job instance.
     *
     * @return void
     */
    private $syncCallBack;
    public function __construct($syncCallBack)
    {
        $this->syncCallBack= $syncCallBack;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $syncCallBack();
    }
}
  • `$syncCallback` isn't defined in that `handle` method. Did you mean `($this->syncCallback)();`? – Jeto Feb 15 '20 at 09:59
  • You use the SerializesModels trait, which means you intend to serialize the object somewhere. But the object is not serializable because of the closure it contains. I'm not sure why you would need to serialize a job. – Olivier Feb 15 '20 at 10:10
  • Is this what you are looking for? https://stackoverflow.com/questions/44409007/any-way-to-dispatch-a-closure-in-laravel-5/46497605 – Jake Zhang Jan 16 '21 at 06:43

0 Answers0