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,开启了队列,最后在执行队列命令,查看数据表验证是否成功。

Laravel 消息通知

  1. 邮件通知
  • 修改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;// 指定邮件接收者
      }
    }
  • 查看邮件,搞定!

Laravel 消息通知

本作品采用《CC 协议》,转载必须注明作者和本文链接
wubuze
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!