Entries tagged serialize

Laravel: Serialization of ‚Closure‘ is not allowed with Jobs and Queues

Posted on 26. Februar 2018 Comments

When dispatching Jobs onto a queue it’s possible to get the following error:

Serialization of ‚Closure‘ is not allowed

This basically means that you are either passing a class that contains anonymous functions („closures“ in PHP) or that in the Job itself there is an anonymous function. This could also be a library you are using. PHP is unable to serialize closures per se. When Jobs get dispatched onto the queue, everything has to be serialized before. If you absolutely must use them this way, look into the Super Closure package by jeremeamia. However, just rewriting the code a little might be easier:



Instead of passing a whole object to the Job like so:

$objOfClassWithClosures = ...;
$job = new Job($objOfClassWithClosures);

Pass the Fully Qualified Class Name (that’s what ClassName::class returns) to the job and instantiate the object on the other side, possibly even using Laravels Container:

$job = new Job(ClassWithClosures::class);

Inside the job you can then use the constructor to make a new instance of that class:

public function __construct(string $fqcn) {
$objOfClassWithClosures = app()->make($fqcn);