我尝试创建一个作业,以便向数据库中的所有用户发送电子邮件我已完成所有操作并成功与 Mailtrip 连接,但在执行命令时仍然有问题:(失败):
PHP artisan queue:work
这是我的 ProductEmail 类:
class ProductMail extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
public $product;
public $user;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct(Product $product, User $user)
{
$this->product = $product;
$this->user = $user;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->subject($this->product->name)
->view('email.product');
}
}
我已经为其创建了视图>>>>
这里是工作类别
class NotifyUsersForProduct implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* @return void
*/
public $product;
public function __construct(Product $product)
{
$this->$product = $product;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$users = User::all();
$users->map(function(User $user){
Mail::to($user)->send(new ProductMail($this->product, $user));
});
}
}
我在这里使用了它
try {
$product = Product::create([
'name' => $request->input('name'),
'price' => $request->input('price'),
'quantity' => $request->input('quantity'),
'user_id' => Auth::id(),
]);
NotifyUsersForProduct::dispatch($product);
public function __construct(Product $product)
{
$this->$product = $product;
}
这应该是:
public function __construct(Product $product)
{
$this->product = $product;
}
删除$ 我也建议这样做,但不是必需的:
public function handle()
{
$users = User::all();
foreach($users as $user){
Mail::to($user)->send(new ProductMail($this->product, $user));
});
}
希望有帮助。
您面临失败的作业,因为即时发送调用邮件,请尝试以下代码,我会进行一些更正来解决您的问题添加延迟方法
class NotifyUsersForProduct implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* @return void
*/
public $product;
public function __construct(Product $product)
{
$this->$product = $product;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
Mail::to($user)->send(new ProductMail($this->product, $user));
}
public function test(){
$delay = 30;
try {
$product = Product::create([
'name' => $request->input('name'),
'price' => $request->input('price'),
'quantity' => $request->input('quantity'),
'user_id' => Auth::id(),
]);
$users = User::all(); // move this code to controller
foreach ($users as $user) {
NotifyUsersForProduct::dispatch($product)->delay($delay);
$delay +=30;
}
}catch(Exception $exception){
}
}
}