Home » Php » php – How can i pass a closure function to a laravel queue dispatch method

php – How can i pass a closure function to a laravel queue dispatch method

Posted by: admin February 25, 2020 Leave a comment

Questions:

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();
    }
}
How to&Answers: