Alexander Kim Alexander Kim - 26 days ago 6
PHP Question

Serialization of 'Closure' is not allowed when using queues

Here's my RequestMail.php file:

protected $phone;

/**
* Create a new message instance.
*
* @return void
*/
public function __construct(Request $request)
{
$this->request = $request;
$this->phone = $request->get('phone');
}

/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->from('robot@bithub.tech')
->view('request')
->subject('Новая заявка на обмен криптовалют')
->with(['phone' => $this->phone]);
}


My controller:

Mail::to('request@domain.com')->queue(new RequestMail($request));


When i am trying to queue the mail, i am getting the following error: "Serialization of 'Closure' is not allowed"

EDIT updated the final code.

Answer Source

If you are using queues you cannot serialize Objects that contains closures, it's the way PHP works. Every time you push a job onto a queue, Laravel serializes its properties to a string that can be written to the database, but anonymous functions (e.g. functions that do not belong to any class) cannot be represented as a string value, thus they cannot be serialized. So basically when you push your RequestMail job onto the queue, Laravel tries to serialize its properties, but $request is an object that contains closures, so it cannot be serialized. To solve the problem you have to store in the RequestMail class only properties that are serializable:

protected $phone;

/**
 * Create a new message instance.
 *
 * @return void
 */
public function __construct(Request $request)
{
    $this->phone = $request->get('phone');
}

public function build()
{
    return $this->from('robot@domain.com')
                ->view('request')
                ->subject('New request for exchange')
                ->with(['phone' => $this->phone]);
}

Doing such thing you are keeping only the properties of $request that you actually need, in this case the phone number, that is a string and it is perfectly serializable.

EDIT I've realized just now that this is a duplicate

EDIT 2 i've edited the code with the correct request parameter retrieval for further reference.