Sending laravel mail containing contents related to the recipient

Viewed 106

How can I send the mail which contains the product details related to a specific company please refer to the code below for further elaboration:

Here is my Controller.php code:

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

Here is my SendCompanyEmail.php code:

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

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

Here is my company-email.blade.php code:

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

I ordered 2 products from 2 different companies and I want an email to be sent to each company with its own product details.

The issue is that when the email is sending, it sends to both companies but with all the products I ordered.

Here is the output email:

To: 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

To: 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

What I actually want is to send the email to both companies but with its respective product details.

Here is the output email I want:

To: company1@company1.com

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

To: company2@company2.com

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

You should group your products by each company.

In your controller, do the grouping logic and send for each email an array of products:

$companiesProducts = [];

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

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

In your email 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');
}

And in your view file change $order->products to the products parameter you've passed.

Related