Skip to content
Advertisement

Laravel : email send multiples times to one user

I want send email to many users in one time but in this case the mail is sending multiple times to one user it self.

Try to email each person one time only(not spam the users) Its didnt work with this method anyone can help n this thing again.

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

                }

Advertisement

Answer

Because you are using nested foreach loop that is why you are facing this issue. If you want to send each template to each user then you can simply swap your loops like:

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

            }
}

Hope this will help!

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement