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

boldstar's avatar

How To Use Mail::setBody() On build()

I would like to pass in a custom email template from database and I have seen where you can use setBody() however when I try to do that I get the following alarm

Call to undefined method App\Mail\StatusUpdate::setBody()

So to send an email I do the following. In my controller

try {
            Mail::to($client->email)->send(new StatusUpdate(['engagement' => $engagement, 'client' => $client]));
    
            return response()->json(['message' => 'The Contact Has Been Notified']);
        } catch(\Exception $e) {
            $e->getMessage();
        }

And then in my StatusUpdate mailable class

public function build()
{
$template = EmailTemplate::where('title', 'Status Update')->first();

        if($sender->has_spouse == true) {
            $spouse_email = $sender->spouse_email;
            return $this->replyTo($email, $name)
                        ->cc($spouse_email)
                        ->bcc($email, $name)
                        ->subject($template->subject . $account->business_name)
                        ->setBody($template->html_template, 'text/html')
        };
}

Should I instead pass another parameter in on my controller method Mail::to?

0 likes
3 replies
boldstar's avatar

@bobbybouwmann , So I ended up going with a hacky option for now, but would be nice for some feedback. I wanted to be able to use templates from database that could render data variables as well. The common way to create a view for a email template is with the view('your_view')->with([ 'data' => $data ]) however because my template would be coming from the database and not from the resources/views directory I had to figure out how I could dynamically render the view from the database and for now I have come to this simple solution. Have not tested in production though

file_put_contents('../resources/views/email.blade.php', $template->html_template)

$template coming from the database.

file_put_contents() will overwrite the current file everytime.

public function build()
{
        $template = EmailTemplate::where('title', 'Status Update')->first();
        file_put_contents('../resources/views/email.blade.php', $template->html_template);

        if($sender->has_spouse == true) {
            $spouse_email = $sender->spouse_email;
            return $this->replyTo($email, $name)
                        ->cc($spouse_email)
                        ->bcc($email, $name)
                        ->subject($template->subject . $account->business_name)
                        ->view('email')
        };
}

view('email') being the file created by file_put_contents()

Please or to participate in this conversation.