Search code examples
phplaravellaravel-5laravel-7

Sends email twice on every request (laravel 7.0)


Hello everyone,

I am using laravel 7.0. I am facing a bug, the email send twice on every request. I checked my code again and again but not found any mistake. below I am adding code

here is controller method controller fetches user and sends email

public function __invoke(Request $request)
{
   try{
        $user = User::all()->first();
            
            if($user->language == 'enUS'){
                $emailTemplate = email_template::whereType('information_en')->first();   
            }else if($user->language == 'deDE'){
                $emailTemplate = email_template::whereType('information_de')->first();
            }
            $templateBody = $emailTemplate->body;
            $templateBody = str_replace('#Title#',  $user->title, $templateBody);
            $templateBody = str_replace('#LastName#', $user->lname, $templateBody);

            $data = [];
            $data['email'] = $user->email;
           
            $data['subject'] = $emailTemplate->subject;
            $data['body'] = $templateBody;
            Mail::to($user->email)->send(new EmailSenderMail($data));
            
            return  "<div>Email has been sent to all user.</div>";
    } catch (\Exception $e) {
        
        return $e->getMessage();
    }
    
}

here is mail class

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class EmailSenderMail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public $data;
    public function __construct($data){

        $this->data = $data;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('email.EmailSender')
        ->subject($this->data['subject'])
        ->with([
                'EmailSenderBody' => $this->data['body'],
            ]);
    }
}*

Solution

  • Problem solved.

    If I use Redirect statement instead of return statement then my problem is solved