4
votes

I'm trying to set up email function for my Laravel project. I've done all the set up, Mailable class, Mailgun, controller for sending the mail, etc.

I've gone through the Laravel mail documentation, and tried to do as it suggested, using a blade template for my mail etc.

The thing is, my clients are going to make their own mails using a WYSIWYG editor, so I can't just make the mail templates in blade.php. I want to get the mail content from the database, and then inject that into a blade file, which I've managed to succeed with.

But let's say the mail content is "Hello {{$name}}", when I get that from the database and inject it into the blade template, the mail that is sent acutally says "Hello {{$name}}" instead of "Hello John Doe". I am sending the $name in my Mailable class, in the build function.

class Confirmation extends Mailable
{
  use Queueable, SerializesModels;

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

   /**
    * Build the message.
    *
    * @return $this
    */
   public function build()
   {
     return $this->from('[email protected]')
                 ->with([
                     'name' => $this->customer->name,
                     'content' => $this->mail_content->content,
                 ])
                 ->subject('Confirmation')
                 ->view('emails.test');
   }
}

So if the content was "Hello {{$name}}", I would like the name from the build function to replace {{$name}} in the content. But since it comes from the database it's apparently not handled the same way as if I just wrote "Hello {{$name}}" in the view file.

My blade template looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Confirmation mail</title>
</head>
<body>
  {!! $content !!}
</body>

Any suggestions? I hope this makes sense to someone out there :D

1
I can't remember exactly how this works but you want to check out Blade::compileString. stackoverflow.com/questions/39801582/…Ty Kroll

1 Answers

1
votes

Could you just use a str_replace() before outputing? http://php.net/manual/en/function.str-replace.php

public function replaceContent() {

    $this->mail_content->content = str_replace('{{$name}}', $this->customer->name, $this->mail_content->content)

}

and call it in your build function

public function build(){

    $this->replaceContent();

    return $this->from('[email protected]')
        ->with([
            'name' => $this->customer->name,
            'content' => $this->mail_content->content,
        ])
        ->subject('Confirmation')
        ->view('emails.test');
}