Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel-5 how to send email from templates stored in db

How can I send email templates which are stored in a database using Laravel-5?

I am using the following code currently:

/* Queue thank you email for sending */

Mail::queue('emails.orderthankyou', $order->get()->first()->toArray(), function ($message) {
    $message->to('[email protected]')->subject('Thank you for your order');
});

However, currently the above template is pulled from the Resources/views directory. I need to change this as my email templates are now stored in a database, like so:

Dear {{ $first_name }},<br><br>

Thank you for your order.

How can I pull these templates from the database and render them to be sent using Mail::Queue?

Thanks in advance.

like image 584
V4n1ll4 Avatar asked Feb 10 '23 14:02

V4n1ll4


1 Answers

First you need to compile your template from string, if you need to use blade syntax on the string template see for example: https://github.com/TerrePorter/StringBladeCompiler

If you don't need any difficult operations, just replacing first name etc., i would go with:

// This will extract your array to variables like $first_name = 'John'
extract($order->get()->first()->toArray());
$generated = "Dear $first_name,<br><br>
            Thank you for your order.";

Now in the message

Mail::queue([], [], function ($message) use ($generated)
{
    $message->queue('[email protected]')
        ->subject('Thank you for your order')
        ->setBody($generated, 'text/html');
});

Notice, that Mail::queue/send first paramater is empty array, there is also setBody() method, where you first pass the generated html and then just tell it the format as text/html.

like image 193
rozklad Avatar answered Feb 12 '23 14:02

rozklad