自定义 Laravel 通知电子邮件模板(页眉和页脚)
最初 Laravel 将使用它们隐藏在框架核心中的组件,您可以通过这样做来导出
php artisan vendor:publish --tag=laravel-mail
它将在您的资源/视图/供应商文件夹中创建一个邮件和降价文件夹。在里面你会发现布局或标题等组件。
创建通知
您想要做的是创建通知、事件或邮件类,以便在发生某些事情时触发电子邮件。
我决定带着通知去。创建任何通知时(您可以阅读有关如何通过 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'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
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]);
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
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
您现在可以轻松地将任何图像添加到您的页眉或更改页脚内的链接等。
希望这会有所帮助。