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

时间:2019-03-01 18:54:31

标签: laravel email notifications

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

我想要的是这段代码:

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

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

3 个答案:

答案 0 :(得分:4)

是否有任何人通过via()方法进行了检查: https://laravel.com/docs/6.x/notifications#specifying-delivery-channels

public function via($notifiable)
{
        // $notifiable object is User instance for most cases
        $wantsEmail = $notifiable->settings['wants_email']; // your own logic
        if(!$wantsEmail){
            // no email only database log
            return ['database'];
        }
        return ['database', 'mail'];
}

我希望这在向多个用户发送通知时也能起作用。谢谢

答案 1 :(得分: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();

答案 2 :(得分:0)

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

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
        );
    }