Laravel:如何从控制器传数组到Markdown邮件模板并循环渲染表格
Fix: Render Cart Items in Laravel Markdown Email Table
Let's walk through fixing this step by step — the core issue is how you're processing the cart data in your controller and then looping through it in the email template.
Step 1: Fix the Controller's Cart Data Handling
Your current code incorrectly tries to extract single values from the $panier array (which is a collection of multiple items). Instead, just pass the entire cart array directly to your Mailable class:
public function store(Request $request) { $phone = $request->phone; $email = $request->email; $address = $request->address; $panier = $request->panier; // This is already an array of cart items $total = $request->total; $data = [ 'phone' => $phone, 'email' => $email, 'address' => $address, 'total' => $total ]; if ($request){ // Pass the full cart array to the Mailable Mail::to($email)->send(new SendInvoice($data, $panier)); } }
Step 2: Update the Mailable Class (Optional but Cleaner)
You can adjust the variable name in your Mailable to be more intuitive (though this isn't strictly required):
class SendInvoice extends Mailable{ use Queueable, SerializesModels; public $data, $panier; public function __construct($data, $panier) { $this->data = $data; $this->panier = $panier; // Use $panier instead of $data_panier for clarity } public function build() { return $this->from('noreply@mail.com', 'Mailer') ->subject('New Order Confirmation') ->markdown('mail.send-invoice'); } }
Step 3: Loop Through Cart Items in the Markdown Template
Use Blade's @foreach directive to dynamically render each cart item as a table row. We'll also add a total row for clarity:
@component('mail::message') # Your Order Confirmation Hi there, here are the details of your recent order: @component('mail::table') | Product Name | Quantity | Price | | ------------- |:-------------:| --------:| @foreach($panier as $item) | {{ $item['name'] }} | {{ $item['quantite'] }} | {{ $item['prix'] }} | @endforeach | **Order Total** | | {{ $data['total'] }} | @endcomponent @component('mail::button', ['url' => '']) View Your Order @endcomponent Thanks for shopping with us,<br> {{ config('app.name') }} @endcomponent
Key Fixes Explained:
- Controller: We stopped trying to split the cart array into individual fields — instead, we pass the full list of items directly to the email.
- Template: The
@foreachloop iterates over each item in the$panierarray, creating a table row for every product in the cart. - Clarity: Renamed variables to be more readable, and added a formatted total row to the table.
内容的提问来源于stack exchange,提问作者therealwalim
相关产品推荐
相关产品推荐

