在Laravel中发送电子邮件通知之前检查用户设置

问题描述 投票:3回答:2

我在Laravel应用程序的User模型中有一个receiveEmail布尔字段。如何确保邮件通知尊重此字段,并且只有在字段为真时才将电子邮件发送给用户?

我想要的是这段代码:

$event = new SomeEvent($somedata);
Auth::user()->notify($event);

其中SomeEvent是一个扩展Notification并在via()方法上实现'mail'的类,只有在用户允许发送电子邮件时才发送电子邮件。

laravel email notifications
2个回答
0
投票

尝试在这样的用户模型中创建新方法..

用户模型文件..

public function scopeNotifyMail() {
        if($this->receiveEmail == true) { //if field is enable email other wise not send..
            $event = new SomeEvent($somedata);
            $this->notify($event);
        }    
}

现在在控制器中这样调用..

Auth::user()->notifyMail();

要么

App\User::find(1)->notifyMail();

要么

App\User::where('id',1)->first()->notifyMail();

0
投票

我最终创建了一个实现检查的新Channel。在应用/频道中,添加您的频道,如下所示:

namespace App\Channels;

use App\User;
use Illuminate\Notifications\Channels\MailChannel;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Arr;

class UserCheckMailChannel extends MailChannel
{
    /**
     * Send the given notification.
     *
     * @param  mixed  $notifiable
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return void
     */
    public function send($notifiable, Notification $notification)
    {
        // check if user should receive emails. Do whatever check you need here.
        if ($notifiable instanceof User && !$notifiable->receiveEmails) {
            return;
        }
        // yes, convert to mail and send it
        $message = $notification->toMail($notifiable);
        if (!$message) {
            return;
        }

        parent::send($notifiable, $notification);
    }
}

然后将Providers/AppServiceProvider.php上的类绑定到旧邮件类:

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()

        $this->app->bind(
            \Illuminate\Notifications\Channels\MailChannel::class,
            UserCheckMailChannel::class
        );
    }
© www.soinside.com 2019 - 2024. All rights reserved.