使用队列时不允许序列化“关闭" [英] Serialization of 'Closure' is not allowed when using queues
问题描述
这是我的RequestMail.php文件:
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]);
}
我的控制器:
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 更新了最终代码.
推荐答案
如果使用队列,则无法序列化包含闭包的对象,这就是PHP的工作方式.每次将作业推送到队列时,Laravel会将其属性序列化为可以写入数据库的字符串,但是匿名函数(例如,不属于任何类的函数)不能表示为字符串值,因此它们不能被序列化.因此,基本上,当您将RequestMail
作业推入队列时,Laravel尝试序列化其属性,但是$request
是一个包含闭包的对象,因此无法序列化.要解决此问题,您只必须在可序列化的属性中存储RequestMail
类:
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]);
}
这样做,您仅保留了实际需要的$request
属性,在这种情况下为电话号码,它是一个字符串,可以完全序列化.
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
编辑2 我已经使用正确的请求参数检索来编辑代码,以供进一步参考.
EDIT 2 i've edited the code with the correct request parameter retrieval for further reference.
这篇关于使用队列时不允许序列化“关闭"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!