Laravel 消息通知
除了支持 发送邮件之外,Laravel 还支持通过多种频道发送通知,包括邮件、短信 (通过 Nexmo),以及 Slack。通知还能存储到数据库以便后续在 Web 页面中显示。
- 下面只记录了常用的邮件通知和database 保存.
1. 保存到数据库
- 创建一个通知类
php artisan make:notification TestNotify
这条命令会在 app/Notifications 目录下生成一个新的通知类。这个类包含 via 方法以及一个或多个消息构建的方法 (比如 toMail 或者 toDatabase) ,它们会针对指定的渠道把通知转换为对应的消息
TestNotify类内容如下
<?php namespace App\TestNotify; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; class TestNotify extends Notification implements ShouldQueue { use Queueable; public function __construct() { } //对应发送的通道 public function via($notifiable) { return $notifiable->db ? ['database'] : ['mail']; } public function toMail($notifiable) { } //存储数据到表,data字段,json格式保存 public function toArray($notifiable) { return [ "name" => "test", "age" => "test", "id" => $notifiable->id, //$notifiable 实例实际上就是User ]; } }
创建通知表 notifications
php artisan notifications:table || php artisan migrate
控制器中发起通知, 下面只介绍使用 Notification Facade 方式
$user =User::find(1); $user->db = true; //指定存储到数据表 \Notification::send($user, new TestNotify());
因为TestNotify,开启了队列,最后在执行队列命令,查看数据表验证是否成功。
- 邮件通知
- 修改TestNotify 类的toMail 方法
public function toMail($notifiable) { return (new MailMessage) ->subject("laravel通知") ->line('你好,这是一条测试通知') ->action('请查看', url('/')) ->line('打扰了'.$notifiable->id); }
同上调用通知类
$user =User::find(2); \Notification::send($user, new TestNotify());
如果有必要指定请指定邮箱字段
class User extends Model { public function routeNotificationForMail() { return $this->email;// 指定邮件接收者 } }
查看邮件,搞定!
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: