How to send an array from Controller to mailable markdown template and loop it in a table component with Laravel?

  arrays, email, laravel, markdown, php

I want to send an array (a sort of shopping cart hardcoded) from my Controller to mailable markdown template and loop it in a table component in a way to have several lines containing all my commands.

I send this data from my view with a POST request :

commande = {
    "phone":"+213582828193",
    "email":"[email protected]",
    "address":"2 rue albert camus",
    "panier": [
        { "name":"Ford", "quantite":"2", "prix":"2000da" },
        { "name":"Ford", "quantite":"2", "prix":"2000da" },
        { "name":"Ford", "quantite":"2", "prix":"2000da" },
        { "name":"Ford", "quantite":"2", "prix":"2000da" },
        { "name":"Ford", "quantite":"2", "prix":"2000da" },
        { "name":"Ford", "quantite":"2", "prix":"2000da" },
    ],
    "total":20
}

I receive data to my controller and it display correctly I can access to all data even the $panier array :

public function store(Request $request)
{

    $phone = $request->phone;
    $email = $request->email;
    $address = $request->address;
    $panier = $request->panier;
    $total = $request->total;

    $data_panier = [
      'name'=> json_decode($panier['name']) ,
        'quantite'=> $panier['quantite'],
        'prix'=> $panier['prix'],
    ];

    $data = [
        'phone' => $phone,
        'email' => $email,
        'address' => $address,
        'total'=>$total
    ];
    //dd($panier[0]["name"]);

    if ($request){
        //Send Email
        Mail::to($email)->send(new SendInvoice($data, $data_panier));
    }
}

My Mailable class where I try to send my $data_panier array :

class SendInvoice extends Mailable{
use Queueable, SerializesModels;

/**
 * Create a new message instance.
 *
 * @return void
 */
public $data,$data_panier;
public function __construct($data, $data_panier)
{
    $this->data = $data;
    $this->data_panier = $data_panier;
}

/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    return $this->from('[email protected]', 'Mailer')->subject('New command')->markdown('mail.send-invoice');
}}

An finally my e-mail template where I want to display my $data_panier with all the data inside in a foreach loop but I don’t know how and I didn’t find documentation or help on how to do that :

@component('mail::message')
Introduction

The body of your message.
@component('mail::table')
| Laravel       | Table         | Example  |
| ------------- |:-------------:| --------:|
| {{ $data_panier['name'] }}      | {{ $data_panier['quantite'] }}      | {{ $data_panier['prix'] }}      |
| Col 3 is      | Right-Aligned | $20      |
@endcomponent

@component('mail::button', ['url' => ''])
Button Text
@endcomponent

Thanks,<br>
{{ config('app.name') }}
@endcomponent

Thank you in advance !

Source: Laravel

Leave a Reply