Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

phpmaven's avatar

Render mail template to a variable

I'm using the following to send an email:

        Mail::send('emails.customerOrder', $customerDetails, function ($message) use ($customerDetails) {
            $message->to($customerDetails['billing_email'])
                    ->from('[email protected]', 'Test Company')
                    ->subject('Your Test Company Order');
        });

$customerDetails is an array and in the template I'm able to refer to the elements of the array as separate variables. For example I have $customerDetails['shipping_method'] and in the email template I can just refer to $shipping_method. I want to save the output of the template to a variable so that I can save a copy of the email to a database.

I tried to do this:

        $view = View::make('emails.customerOrder')->with('customerDetails', $customerDetails);

        $contents = $view->render();

And it fails because the template now expects that the variables will be referenced like a normal array value. It expects $customerDetails['shipping_method'] and doesn't recognize $shipping_method.

What's the best way to get a copy of the rendered email?

Thanks,

Mark

0 likes
2 replies
bobbybouwmann's avatar

Yeah, that doesn't work, because the variable you pass to the view is also the one that is available. If you want to do to pass in the data from that array to the view per key value you have to do something like this

$view = View::make('emails.customerOrder')

foreach ($customerDetails as $key => $value) {
    $view->with($key, $value);
}

$contents = $view->render();

This way you have the correct result, because you pass each item of the array to the view.

Please or to participate in this conversation.