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

MichaelGrossklos's avatar

Serialization of 'Closure' is not allowed

Hi,

since I#m using ShouldBeQueued in my Commands I get this error:

Exception in Queue.php line 91:
Serialization of 'Closure' is not allowed

I tried it with

use SerializesModels;

But it didn't work either.

Do you have any idea what's going wrong?

0 likes
22 replies
toniperic's avatar

Showing the code would be helpful in debugging this.

MichaelGrossklos's avatar
<?php namespace App\Commands;

use App\Commands\Command;

use App\Events\UserHasRegistered;
use App\Http\Helpers\Helpers;
use App\Http\Requests\UsersRequest;
use App\User;
use Event;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Queue\SerializesModels;


class UserRegisterCommand extends Command implements SelfHandling {

    use SerializesModels;

    /**
     * @var
     */
    private $request;

    /**
     * Create a new command instance.
     *
     * @param                           $request
     * @param \App\Http\Helpers\Helpers $helpers
     *
     * @return \App\Commands\UserRegisterCommand
     */
    public function __construct(UsersRequest $request)
    {
        $this->request = $request;
    }

    /**
     * Execute the command.
     *
     * @param \App\User|\User           $user
     *
     * @param \App\Http\Helpers\Helpers $helpers
     *
     * @internal param \UserRegisterCommand $event
     *
     * @internal param $request
     *
     * @return void
     */
    public function handle(User $user, Helpers $helpers)
    {
        $this->registerUser($user, $helpers);

      //Event::fire(new UserHasRegistered($user));
    }

    /**
     * @param \App\User                 $user
     * @param \App\Http\Helpers\Helpers $helpers
     */
    private function registerUser ( User $user, Helpers $helpers )
    {
        $password = $helpers->createCrypticString(8);

        $user->create([
            "firstname" => $this->request->get('firstname'),
            "lastname"  => $this->request->get('lastname'),
            "email"     => $this->request->get('email'),
            "password"  => bcrypt($password)
        ]);
    }

}
MichaelGrossklos's avatar

In the UserController:

 /**
     * Store a newly created resource in storage.
     *
     * @uses     createCrypticString() from Helpers.php
     *
     * @param \App\Http\Requests\UsersRequest $request
     *
     * @internal param \App\Commands\UserRegisterCommand $command
     *
     * @return Response
     */
    public function store (UsersRequest $request)
    {
        $this->dispatch(new UserRegisterCommand($request));

        flash()->success( trans('messages.user_added') );

        return redirect('users');
    }
brlebtag's avatar

I was trying to use Mailer in my Command and a command will be serialized and deserialized when needed, but Mailer has many clousures so it can't be serialized. Maybe somewhere your using clouseres or have components that use them so it can't be serialized too.

1 like
pavankumar's avatar

Same problem here, request object is not serializing.

mkaufman's avatar

Same problem here, request object is not serializing.

arseneoaa's avatar

I had that issue and solved it.

It was because I was doing $job = new SendNewSignUpEmail($request);

Just changed that to : $job = new SendNewSignUpEmail($request->all());

SendNewSignUpEmail is just a job.

14 likes
briedis's avatar

Came across this on 5.2. All your routes need to be in this format:

Route::get('route')->uses('controller@css')->name('route-name');

If your routes are something else, in the old style for example, you will get a closure serialization error

Route::get('route', ['uses' => 'controller@...', 'as' => '..']);
1 like
shez1983's avatar

@briedis that happens when you try to OPTIMIZE your app ie php artisan optimize.. and their problem isnt related to that

2 likes
ako_salman's avatar

I had the same issue. For me it was because of running :

$this->order_repository = resolve('App\Services\Repositories\OrderRepository');

in the constructor of the job. Resolving an instance of OrderRepository from it's interface and add it to Job's class caused serializing that repository instance and the problem was with serializing that instance. As there is no need for repository to be instantiated in the constructor of the Job's class, i puted it in the handle method and the issue solved. Generally each piece of data you attach to the Job's class will be serialized, so you must be aware that your date could be serialized without any issues.

2 likes
enderandpeter@yahoo.com's avatar

This happened to me when I was trying to pass an object to the ShouldQueue handle method whose class members defined Closures. When I replaced the object with one made from a much simpler class whose properties were only scalar data, there was no issue.

metallurgical's avatar

This happened to me because i instantiated new class inside constructor method of Job class. To cope this issue, i instantiated it inside of "handler" method and the error gone

4 likes
ehben's avatar

Use dependency injection in the handler method to solve this.

dev-techguy's avatar

The solution is to pass the request instance like this

public function stkPushQuery(MpesaQueryRequest $request)
{
    // Correct way of doing it
    dispatch(new MpesaQueryJob(
        (new MpesaQueryRequest)
    ))->onQueue('default');

    // This one will through an error of Serialization
    dispatch(new MpesaQueryJob(
        $request
    ))->onQueue('default');

    return $this->successResponse([
        'message' => 'Accepted for processing...'
    ]);
}
Snapey's avatar

you would not want to put the whole request object on the queue anyway. That thing is huge

1 like
NitinDev's avatar

If you experience the issue 'Serialization of 'Closure' is not allowed,' I have a solution to resolve it. This problem arises when attempting to serialize data that is not in the correct format, such as passing an object containing closures. To fix it, ensure that the data passed is in a serializable format, such as an array exmaple

when you  directlly pass the data to job dispatch then encounter the error 
  'Serialization of 'Closure' is not allowed,'

public static function applyAdminSettingsToPartners($requestsData) { SyncPartnerCampaignSettings::dispatch($requestsData); }

then i format the data like return $requestsData; ['adminCategoryId' => $adminCategoryId, 'adminCampaignTypeId' => $adminCampaignTypeId, 'adminIndustryId' => $adminIndustryId] = $requestsData;

   SyncPartnerCampaignSettings::dispatch($adminCategoryId,$adminCampaignTypeId,$adminIndustryId);

Please or to participate in this conversation.