Serialization of 'Closure' is not allowed when using queues

霸气de小男生 提交于 2019-12-08 10:40:03

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/46423512/serialization-of-closure-is-not-allowed-when-using-queues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!