Laravel技巧集锦(33):使用notification实现站内通知(邮件)

准备:会使用sendcloud发送邮件 https://blog.csdn.net/sinat_37390744/article/details/88738359

1、app\Notifications\NewUserFollowNotification.php中指定通知类型为email

<?php

namespace App\Notifications;

use App\Channels\SendcloudChannel;  //引入邮件处理
use App\Mailer\UserMailer;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Facades\Auth;
use Naux\Mail\SendCloudTemplate;
class NewUserFollowNotification extends Notification
{
    use Queueable;

    public function __construct()
    {
        //
    }

//先database执行toDatabase方法;再sendcloud执行toSendcloud方法
    public function via($notifiable)
    {
        return ['database',SendcloudChannel::class];//默认的Mail不支持sendcloud,但可以自定义channel
    }


//自定义的方法,在channel中使用
    public function toSendcloud($notifiable){

//封装好的发送邮件类
        (new UserMailer())->followNotifyEmail($notifiable->email);
    }

    public function toDatabase($notifiable){
        return [
            'name' => \Auth::guard('api')->user()->name,

        ];
    }
   
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

2、app\Channels\SendcloudChannel.php中(自定义notifications的channel)

<?php

namespace App\Channels;

use Illuminate\Notifications\Notification;

class SendcloudChannel
{
    public function send($notifiable,Notification $notification){
        $message = $notification->toSendcloud($notifiable);//Notification自定义的方法
    }
}

3、将邮件发送作为基类

app\Mailer\Mailer.php中

namespace App\Mailer;

use Naux\Mail\SendCloudTemplate;
class Mailer
{
    public  function sendTo($template,$email,array $data){

        $content =new SendCloudTemplate($template,$data);
        \Mail::raw($content,function ($message) use ($email){
            $message->from('mail@itchuan.net','IThchuan');
            $message->to($email);
        });
    }

}

app\Mailer\UserMailer.php继承上面的基类

namespace App\Mailer;

use App\User;

class UserMailer extends Mailer
{

    public function followNotifyEmail($email){
        $data = [
           
        ];

        $this->sendTo('follow_user_templete',$email,$data);//使用基类的发送邮件方法
    }


    public function passwordReset($email,$token){
        $data = [
           
        ];

        $this->sendTo('pwd_reset_template',$email,$data);
    }

    public function welcome(User $user){
        $data = [
            
        ];
        $this->sendTo('register_templete',$user->email,$data);

    }
}

4、当用户关注时候:

 $user->notify(new NewUserFollowNotification());

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值