正在发送 laravel 封包含收件人相关内容的邮件

Sending laravel mail containing contents related to the recipient

如何发送包含与特定公司相关的产品详细信息的邮件,请参阅下面的代码以进一步阐述:

这是我的 Controller.php 代码:

    foreach ($order->products as $product){
      foreach ([$product->company_email] as $recipient) {
        Mail::to($recipient)->send(new SendCompanyEmail($order));
      }
    }

这是我的 SendCompanyEmail.php 代码:

public function __construct(Order $order)
{
    $this->order = $order;
}

public function build()
{
    return $this->markdown('emails.company-email')
                ->subject('New Order Placed');
}

这是我公司-email.blade.php代码:

@foreach($order->products as $product)
    Name: {{ $product->name }}
    Price: {{ $product->price }} USD
    Company Email: {{ $product->company_email }}
@endforeach

我从 2 家不同的公司订购了 2 件产品,我希望向每家公司发送一封电子邮件,其中包含各自的产品详细信息。

问题是在发送电子邮件时,它发送给了两家公司,但包含我订购的所有产品。

这是输出电子邮件:

收件人:company1@company1.com

Name:   Product 1
Price:  10.00 USD
Company Email:  company1@company1.com

Name:   Product 2
Price:  12.00 USD 
Company Email:  company2@company2.com

收件人:company2@company2.com

Name:   Product 1
Price:  10.00 USD
Company Email:  company1@company1.com

Name:   Product 2
Price:  12.00 USD 
Company Email:  company2@company2.com

我真正想要的是将电子邮件发送给两家公司,但包含各自的产品详细信息。

这是我想要的输出电子邮件:

收件人:company1@company1.com

Name:   Product 1
Price:  10.00 USD
Company Email:  company1@company1.com

收件人:company2@company2.com

Name:   Product 2
Price:  12.00 USD 
Company Email:  company2@company2.com

您应该按每个公司对产品进行分组。

在您的控制器中,执行分组逻辑并为每封电子邮件发送一组产品:

$companiesProducts = [];

foreach ($order->products as $product) {
    $companiesProducts[$product->company_email][] = $product;
}

foreach ($companiesProducts as $email => $products) {
    Mail::to($email)->send(new SendCompanyEmail($products));
}

在您的电子邮件中 ​​class:

public function __construct($products)
{
    $this->products = $products;
}

public function build()
{
    // pass $this->products to your email view
    return $this->markdown('emails.company-email')
                ->subject('New Order Placed');
}

然后在您的视图文件中将 $order->products 更改为您传递的产品参数。