Laravel : 多次向一个用户发送电子邮件

Laravel : email send multiples times to one user

我想一次性向多个用户发送电子邮件,但在这种情况下,邮件会向一个用户发送多次。

尝试只向每个人发送一次电子邮件(不要向用户发送垃圾邮件) 它不适用于此方法任何人都可以再次帮助解决这个问题。

    public function create() 
    {
        $users = User::where('user_type', 2)->get();
        $auto_email_templates = AutoEmailTemplate::all();

        foreach ($users as $user) {
            foreach($auto_email_templates as $mail){

                if( $user->created_at < Carbon::now()->subDays($mail->days)){

                    Mail::to($user->email)->send(new Automail($mail));
                    $mail = new EmailSave;
                    $mail->user_id = $user->id;
                    $mail->email_id =$mail->id;
                    $mail->save();
                }
            }   
        }       
    }

public function create() 
    {
        $users = User::where('user_type', 2)->get();
        $auto_email_templates=AutoEmailTemplate::all();


        foreach($auto_email_templates as $mail) {
            foreach ($users as $user) {


                if( $user->created_at < Carbon::now()->subDays($mail->days)){

                    if (EmailSave::where('email_id', '=', Input::get('email_id'))->exists()) {
                        Mail::to($user->email)->send(new Automail($mail));
                    }
                   else {  
                       return false;
                   }               

                    $mail = new EmailSave;
                    $mail->user_id = $user->id;
                    $mail->email_id =$mail->id;
                    $mail->save();

                }

因为您正在使用嵌套的 foreach 循环,这就是您遇到此问题的原因。如果您想将每个模板发送给每个用户,那么您可以简单地交换循环,例如:

public function create() 
{
    $users = User::where('user_type', 2)->get();
    $auto_email_templates=AutoEmailTemplate::all();



  foreach($auto_email_templates as $mail){ 
       foreach ($users as $user) { // add this to here

            if( $user->created_at < Carbon::now()->subDays($mail->days)){

                Mail::to($user->email)->send(new Automail($mail));


                $mail = new EmailSave;
                $mail->user_id = $user->id;
                $mail->email_id =$mail->id;
                $mail->save();

            }
}

希望对您有所帮助!