composer require "wpb/string-blade-compiler"
メールテンプレートを保存しているテーブル設計は以下とする。
CREATE TABLE `mail_templates` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`sort` tinyint unsigned NOT NULL COMMENT '種類',
`type` enum('text','html') COLLATE utf8mb4_unicode_ci NOT NULL COMMENT 'タイプ',
`template` text COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `mail_templates_sort_type_unique` (`sort`,`type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
以下「TestMail.php」について、特筆すべき点が無い部分は省略。
(省略部分は元々の記載をそのまま使えば問題ないです)
app\Mail\TestMail.php
class TestMail extends Mailable
{
public $text_template;
public $html_template;
public $user;
public function __construct($user)
{
$this->user= $user;
}
public function build()
{
// sort 1 がフッターとする
$mail_footers = MailTemplate::where('sort', 1)
->pluck('template', 'type')
->toArray();
// sort 2 がメールのテンプレートとする
$mail_templates = MailTemplate::where('sort', 2)
->pluck('template', 'type')
->toArray();
if (is_null($mail_templates)) {
return;
}
if (isset($mail_templates['text'])) {
$this->text_template = view([
'template' => $mail_templates['text'],
], [
'user' => $this->user,
'footer' => $mail_footers['text'] ?? '',
])->render();
$this->text('mail.text');
}
if (isset($mail_templates['html'])) {
$this->html_template = view([
'template' => $mail_templates['html'],
], [
'user' => $this->user,
'footer' => $mail_footers['html'] ?? '',
])->render();
$this->view('mail.html');
}
return $this->subject('test');
}
}
※ 説明を簡潔にするため、上記コード内で sort の数字を直接記載しているが、本来は定数を使う
resources\views\mail\text.blade.php
{!! $text_template !!}
resources\views\mail\html.blade.php
{{ $html_template }}
コメント