如何自定义Laravel通知邮件模板(头部和底部)
Laravel最初会使用其内核中隐藏的组件,您可以通过执行以下操作导出这些组件:
php artisan vendor:publish --tag=laravel-mail
它将在你的resources/view/vendor文件夹下创建一个mail和markdown文件夹。在里面,你会找到像layout或header等组件。
创建通知
你想做的是创建一个通知、事件或邮件类,以便在发生某些事情时触发电子邮件。
我决定使用通知。创建任何通知时(您可以通过artisan了解更多有关如何创建通知的信息),您将获得一个类似以下内容的类:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class UserRegistered extends Notification {
use Queueable;
public $user;
public function __construct($user) {
$this->user = $user;
}
public function via($notifiable) {
return ['mail'];
}
public function toMail($notifiable) {
return (new MailMessage)
->from('info@sometimes-it-wont-work.com', 'Admin')
->subject('Welcome to the the Portal')
->markdown('mail.welcome.index', ['user' => $this->user]);
}
public function toArray($notifiable) {
return [
];
}
}
请注意toMail方法以及类的构造函数,因为我们将向其传递一个对象。还要注意,我们正在使用->markdown('some.blade.php');
下一步是将此通知推送到工作区。在您的RegisterController中的某个地方,您可能想调用此函数(不涉及如何执行它,无论是同步还是排队...)。不要忘记在顶部包含通知的命名空间。
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'lastname' => $data['lastname'],
'password' => bcrypt($data['password']),
]);
$user->notify(new UserRegistered($user));
为什么我要深入探讨呢?因为我还想向你展示如何将数据传递到电子邮件模板中。
接下来,你可以打开 resources/views/mail/welcome/index.blade.php(可以是任何文件夹和文件名),并复制粘贴以下内容:
@component('mail::layout')
{{-- Header --}}
@slot('header')
@component('mail::header', ['url' => config('app.url')])
Header Title
@endcomponent
@endslot
{{-- 正文 --}}
这是我们的主要信息 {{ $user }}
{{-- Subcopy --}}
@isset($subcopy)
@slot('subcopy')
@component('mail::subcopy')
{{ $subcopy }}
@endcomponent
@endslot
@endisset
{{-- Footer --}}
@slot('footer')
@component('mail::footer')
© {{ date('Y') }} {{ config('app.name') }}. Super FOOTER!
@endcomponent
@endslot
@endcomponent
现在您可以轻松地将任何图像添加到标题中,或更改页脚中的链接等。
希望这可以帮到您。