Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lozadakb's avatar

Using methods inside Bus::batch ->then

I have a command that runs a batch of jobs like this:

$batch = Bus::batch($jobs)
                    ->then(function (Batch $batch) use ($reportId) {
                        $this->removeDuplicatedEmails();
                        $this->assignBonus($reportId);
                    })   
                    ->dispatch();

When I call the removeDuplicatedEmails and assignBonus functions inside ->then, I get this serialization error:

[2023-06-19 13:19:03] local.ERROR: Cannot assign Laravel\SerializableClosure\Serializers\Native to property Symfony\Component\Console\Input\InputArgument::$suggestedValues of type Closure|array {"exception":"[object] (TypeError(code: 0): Cannot assign Laravel\SerializableClosure\Serializers\Native to property Symfony\Component\Console\Input\InputArgument::$suggestedValues of type Closure|array at /var/www/html/vendor/laravel/serializable-closure/src/Serializers/Native.php:287) 

However, if I put the code inside those functions directly into ->then, it works without any problems.

Additionally, when I execute the batch with these functions from inside a controller, it also works correctly.

Why am I getting this serialization error, and how can I fix it?

0 likes
3 replies
Niush's avatar

Since batch callbacks are serialized and executed at a later time by the Laravel queue, you should not use the $this variable within the callbacks. https://laravel.com/docs/9.x/queues#dispatching-batches

Serializer does not know the context of $this. Try something like:

ReportService::removeDuplicatedEmails();
BonusService::assignBonus($reportId);

Or, you can even dispatch these as another job.

4 likes
bglaskoww's avatar

Wow! yes! Thank you for your answer!

edit: It worked for me as well

1 like

Please or to participate in this conversation.